串口编程:请问VB 中 怎么把浮点数转换为十六进制的Byte型
答案:1 悬赏:0 手机版
解决时间 2021-02-17 22:55
- 提问者网友:献世佛
- 2021-02-17 13:28
请问VB 中 怎么把浮点数转换为十六进制的Byte型 . 我做的是串口编程
最佳答案
- 五星知识达人网友:掌灯师
- 2021-02-17 13:51
VB转化这个东西有点烦。我以前做过的一段代码如下(验证过的):
Public Function funSignSngTo4Byt(SingleData As Single) As Boolean
'高位在前,低位在后
Dim i, d As Integer
Dim PorN As Byte
Dim ExpVal, temp As Long
Dim FraVal, t1 As Long
Dim SingleFra, tempval As Single
If SingleData = 0 Then
For i = 0 To 3
gbytBinData(i) = 0
Next i
Exit Function
End If
If SingleData >= 0 Then '符号位
PorN = 0
Else
PorN = &H80
SingleData = -1 * SingleData '变为正数
End If
ExpVal = Int(Log(SingleData) / Log(2)) '指数
If ExpVal > 128 Then
funSignSngTo4Byt = False
Exit Function
End If
If ExpVal = 127 Then
SingleFra = SingleData / (2 ^ ExpVal)
Else
SingleFra = SingleData / (2 ^ ExpVal) - 1
End If
FraVal = Int(SingleFra * 128 * 256 * 256) And &HFFFFFF
ExpVal = ExpVal + 127
gbytBinData(0) = PorN + ExpVal \ 2
gbytBinData(3) = FraVal And &HFF
FraVal = Int(FraVal \ 256)
gbytBinData(2) = FraVal Mod 256
FraVal = FraVal \ 256
gbytBinData(1) = (FraVal Mod 256) Or ((ExpVal And 1) * 128)
End Function
Public Function funSignSngTo4Byt(SingleData As Single) As Boolean
'高位在前,低位在后
Dim i, d As Integer
Dim PorN As Byte
Dim ExpVal, temp As Long
Dim FraVal, t1 As Long
Dim SingleFra, tempval As Single
If SingleData = 0 Then
For i = 0 To 3
gbytBinData(i) = 0
Next i
Exit Function
End If
If SingleData >= 0 Then '符号位
PorN = 0
Else
PorN = &H80
SingleData = -1 * SingleData '变为正数
End If
ExpVal = Int(Log(SingleData) / Log(2)) '指数
If ExpVal > 128 Then
funSignSngTo4Byt = False
Exit Function
End If
If ExpVal = 127 Then
SingleFra = SingleData / (2 ^ ExpVal)
Else
SingleFra = SingleData / (2 ^ ExpVal) - 1
End If
FraVal = Int(SingleFra * 128 * 256 * 256) And &HFFFFFF
ExpVal = ExpVal + 127
gbytBinData(0) = PorN + ExpVal \ 2
gbytBinData(3) = FraVal And &HFF
FraVal = Int(FraVal \ 256)
gbytBinData(2) = FraVal Mod 256
FraVal = FraVal \ 256
gbytBinData(1) = (FraVal Mod 256) Or ((ExpVal And 1) * 128)
End Function
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯