十六进制数组转换为浮点计算方法两种算法

最近在开发一个串口通讯的项目中,需要将从串口中读出的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());


这样调整后,输出的数据就正确了,当然以后,还会遇到不同厂家的数据顺序的定义。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值