用VB.NET 写十六进制转浮点数据的代码,根据转换原理,编写了一段代码:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim str16 As String = "4145BE77"
'1:
'十六进制转二进制
Dim str16to10 As Integer = Convert.ToInt32(str16, 16) '十六进制转十进制
Dim str10to2 As String = Convert.ToString(str16to10, 2) '十进制转二进制
'2:确定S\E\M
Dim S As String = 0
Dim E1 As String = Mid(str10to2, 1, 8) 'E1
Dim M As String = Mid(str10to2, 9, 23)
Dim str10to2_Length As Integer = Len(str10to2) '二进制字符串个数
'3:
'3-1:二进制E转为整数
Dim str2to10 As Integer = Convert.ToInt32(E1, 2) '二进制转十进制
Dim E2 As Integer = str2to10 - 127 'E2
'3-2:二进制字符M根据E2值,确定小数点位置,再1+M
Dim str2_1 As String = Mid(M, 1, E2) & "." & Mid(M, E2 + 1)
Dim str2_2 As String = “1” & str2_1
'4:
'4-1:二进制字符1+M转化位浮点数据str2to10_1
Dim str2to10_1 As Double = Convert.ToDouble(str2_2)
Dim str2to10_2 As Double
'4-2:根据str2to10_1。计算浮点数据 str2to10_2
Dim 整数 As Integer = 0
Dim 小数 As Double = 0
For i = 1 To E2 + 1
整数 = 整数 + Mid(str2to10_1, i, 1) * 2 ^ (E2 + 1 - i)
Next i
For j = 1 To 23
Try
小数 = 小数 + Mid(str2to10_1, E2 + 3, 1) * 2 ^ (-j)
E2 = E2 + 1
Catch ex As Exception
End Try
Next j
str2to10_2 = (整数 + 小数).ToString("F3")
'Console.WriteLine("十六进制转十进制:" & str16to10)
'Console.WriteLine("十进制转二进制:" & str10to2)
'Console.WriteLine("长度:" & str10to2_Length)
'Console.WriteLine("E1:" & E1)
'Console.WriteLine("M:" & M)
'Console.WriteLine("二进制转十进制:" & str2to10)
'Console.WriteLine("E2:" & E2)
'Console.WriteLine("str2_1:" & str2_1)
'Console.WriteLine("str2_2:" & str2_2)
'Console.WriteLine("整数:" & 整数)
'Console.WriteLine("小数:" & 小数)
Console.WriteLine("str2to10_2:" & str2to10_2)
End Sub
最后运算结果为:
str2to10_2:12.359
欢迎交流!