发布于 2004-08-29 16:57:49
0楼
PLC S7-200中4个字节转换成浮点数,用VB写的
'4字节 → 浮点数
Public Function B2R(ByVal byte1 As Byte, ByVal byte2 As Byte, ByVal byte3 As Byte, ByVal byte4 As Byte) As String
Dim bins As String '二进制字符串
bins = Ten2Two(byte1) & Ten2Two(byte2) & Ten2Two(byte3) & Ten2Two(byte4)
If Len(bins) = 32 Then
Else: MsgBox "字节转换成实数位数不足,出错"
End If
Dim Symbol As Integer '最高符号位
Symbol = Mid(bins, 1, 1)
Dim Factorial As String '8位阶码
Dim Fact As Integer
Factorial = Mid(bins, 2, 8)
Factorial = ToDec(Factorial)
Factorial = Val(Factorial) - 127
Fact = Val(Factorial)
Dim Mantissa As String '23位尾数 启始位 10 位
Mantissa = Mid(bins, 10, 23)
Dim Inte, Deci As String '定义整数部,小数部分 Integer Decimal
If Fact > 0 Then
Inte = Mid(Mantissa, 1, Fact)
Inte = 1 & Inte
Inte = ToDec(Inte)
Deci = Mid(bins, 10 + Fact, 24)
End If
If Fact <= 0 Then
If Fact = 0 Then
Inte = 1
End If
Deci = 1 & Mantissa
Dim i As Integer
For i = 1 To (Abs(Fact) - 1)
Deci = 0 & Deci
Next i
End If
Dim Dec_point As Double ' 小数部分
Dim lenth, j As Integer
lenth = Len(Deci) * -1
Dec_point = 0#
For j = -1 To lenth Step -1
Dec_point = Dec_point + Val(Mid(Deci, -j, 1)) * 2 ^ (j)
Next j
If Symbol = 1 Then
B2R = Format(((Dec_point + Val(Inte)) * -1#), "#.000")
Else: B2R = Format((Dec_point + Val(Inte)) * 1#, "#.000")
End If
End Function