IEEE754 32位单精度4字节16进制数转为10进制数,EXE+VB6.0源码
IEEE754 32位单精度4字节16进制数转为10进制数,VB6.0源码
’ 下列代码演示了10进制Single(单精度浮点型转为16进制字符显示的浮点数和其相反运算:
Option Explicit
Private Declare Sub CopyMemory Lib “kernel32” Alias “RtlMoveMemory” (Destination As Any, Source As Any, ByVal Length As Long) ’ for 转换压力传感器返回值的16进制数为浮点型真是数值,单位为Bar,在Timer_HPLPMPTRTTTS中使用
Private Sub Command1_Click()
'功能:输入4个字节的16进制数,按照IEEE754协议,转化为浮点型真实数值,单位为Bar
Dim sinStr As String
Dim sinSj As Single
Dim HEX2FLOATIEEE754 As Single
Dim buffer(3) As Byte
Dim i As Long
Dim indata_all_4Byte As String
'截取数据段的4个字节的16进制数
Dim Buffer_origin As Variant
Buffer_origin = Text1 'indata_all_origin
indata_all_4Byte = “”
’ For i = 3 To 6 'LBound(indata_all_origin) To UBound(indata_all_origin)
’ indata_all_4Byte = indata_all_4Byte & Buffer_origin(i) 'indata & Chr(inss(j)) '样例,温度反馈值:=+016.78@ ,04 TR通道的应答结果为=+016.1O
’ Next i
sinStr = Buffer_origin
For i = 1 To Len(sinStr) Step 2
buffer((7 - i) / 2) = Val("&H" & Mid(sinStr, i, 2))
Next
CopyMemory ByVal VarPtr(sinSj), ByVal VarPtr(buffer(0)), 4
HEX2FLOATIEEE754 = sinSj ’ 显示真实值
'CopyMemory d, Buffer_origin(0), 4
'IEEE754浮点数的转换方法
’ 1位符号位(SIGN)8位指数位(EXPONENT)23位尾数位(MANTISSA)
'其中,32位二进制数的排位为:[31][30][29]…[2][1][0]
'16进制转换为10进制的公式如下:SGL = (-1)^SIGN * 1.MANTISSA * 2^(EXPONENT-127)
'举例:
'将0x40800000转换为10进制数,方法如下:
'(1)先将16进制数转成二进制数01000000100000000000000000000000
Dim temp_binary As Variant
Dim decimal_float As Single
Dim exponent As Single
Dim decimal_temp As Single
’ 补齐左边的0
Dim len_temp As Integer
len_temp = Len(sinStr)
If len_temp < 8 Then
For i = 1 To 8 - len_temp
sinStr = sinStr & “0”
Next i
End If
'temp_binary = H2B(sinStr)
'Dim i As Long
Dim b As String
Dim Hex_temp As String
Hex_temp = UCase(sinStr)
For i = 1 To Len(Hex_temp)
Select Case Mid(Hex_temp, i, 1)
Case "0": b = b & "0000"
Case "1": b = b & "0001"
Case "2": b = b & "0010"
Case "3": b = b & "0011"
Case "4": b = b & "0100"
Case "5": b = b & "0101"
Case "6": b = b & "0110"
Case "7": b = b & "0111"
Case "8": b = b & "1000"
Case "9": b = b & "1001"
Case "A": b = b & "1010"
Case "B": b = b & "1011"
Case "C": b = b & "1100"
Case "D": b = b & "1101"
Case "E": b = b & "1110"
Case "F": b = b & "1111"
End Select
Next i
'While Left(b, 1) = "0"
'b = Right(b, Len(b) - 1)
'Wend
temp_binary = b
i = Len(temp_binary)
'(2)1位符号位(SIGN)=0
'(3)8位指数位(EXPONENT)=10000001=129[10进制]
exponent = Mid ( t e m p b i n a r y , 2 , 1 ) ∗ 128 + M i d (temp_binary, 2, 1) * 128 + Mid (tempb