1. 用32位表示浮点数
vb 16进制和浮点数互相转换的方法
'IEEE754 浮点数 http://www.doc88.com/p-9902813307216.html, 0.98=3F 7A E1 47 'http://lostphp.com/hexconvert/ Private Function SingleToHex(ByVal fValue As Single) As String Dim AA(3) As Byte Dim HexString As String Dim tmp As String CopyMemory ByVal VarPtr(AA(0)), ByVal VarPtr(fValue), 4 For i = 3 To 0 Step -1 tmp = CStr(Hex(AA(i))) If (Len(tmp) = 1) Then tmp = "0" & tmp End If HexString = HexString & tmp & " " Next SingleToHex = Left(HexString, Len(HexString) - 1) End Function 'IEEE754 浮点数 Private Function HexToSingle(ByVal HexString As String) As Single Dim AA() As Byte Dim BB(3) As Byte Dim fValue As Single AA = HexStringToBytes(HexString) 'reverse array BB(0) = AA(3) BB(1) = AA(2) BB(2) = AA(1) BB(3) = AA(0) CopyMemory ByVal VarPtr(fValue), ByVal VarPtr(BB(0)), 4 HexToSingle = fValue End Function
C#的方法
//4048F5C2 => 3.14 string value = "4048F5C2";//16进制字符串 UInt32 x = Convert.ToUInt32(value, 16);//字符串转16进制32位无符号整数 float fy = BitConverter.ToSingle(BitConverter.GetBytes(x), 0);//IEEE754 字节转换float //3.14=>4048F5C2 var cc = BitConverter.GetBytes(fy); string HexStr= string.Empty; for (int i = 0; i < 4; i++) { HexStr = Convert.ToString(cc[i], 16).ToUpper() + HexStr; }
2. 约定固定小数位数, 比如3.56 ,就*100 =356, 取值时对应就除100
通讯时就取Hex(356)