最近在开发一个串口通讯的项目中,需要将从串口中读出的16进制数据直接转换为浮点数,如16进制字符串“0064128”,如果使用VB来写数据转换是样的
'定义二进制结构
Private Type HexData4
byte1 As Byte
byte2 As Byte
byte3 As Byte
byte4 As Byte
End Type
'定义一单精度结构
Private Type RealData
dataR As Single
End Type
'将二进制格式分别对应写入结构中HexData4,然后赋值计算
Public Function GetReal(B1 As Byte, B2 As Byte, B3 As Byte, B4 As Byte) As Single
On Error GoTo GetReal_Error
Dim HD As HexData4 ' create user defined types for LSet to work on
Dim RD As RealData ' create user defined types for LSet to work on
HD.byte2 = B1
HD.byte1 = B2
HD.byte4 = B3
HD.byte3 = B4
LSet RD = HD
GetReal = RD.dataR
Debug.Print Format(GetReal, "0.00")
Exit Function ' avoid the error handler
GetReal_Error:
Debug.Print "Invalid Real=" & HD.byte1 & " " & HD.byte2 & " " & HD.byte3 & " " & HD.byte4
GetReal = 0
Resume Next
End Function
其结果值为4.000
但在使用c#时,就出现了问题,采用BITCONVERTER,将基础数据类型与字节数组相互转换。这个函数有一个调整顺序的参数(Little-endian,Big-endian) ,一个正序,或序。
string hexString = "0064128";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);
按上面的结果计算的数据是不正确的,因为仪表定义的数据格式不是这种的,为此修改一个数据在数组中的布局
byte[] floatVals = new byte[4];
floatVals[1] = inbyte[1];
floatVals[0] = inbyte[2];
floatVals[3] = inbyte[3];
floatVals[2] = inbyte[4];
float fsum = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("sum float convert = {0}", fsum.ToString());