用VB自带函数进行十六-十进制转换出错!什么原因呢?
用VB自带函数测试结果:
? hex(53211)
CFDB
? &HCFDB
-12325
这两个互换的函数怎么会是这种结果?
********************************************************************
只好用下面的函数了:
Public Function HEX_to_DEC(ByVal Hex As String) As Long
'用途: 将十六进制转化为十进制
' 输入:Hex(十六进制数)
' 输入数据类型:String
' 输出:HEX_to_DEC(十进制数)
' 输出数据类型:Long
Dim i As Long
Dim B As Long
Hex = UCase(Hex)
For i = 1 To Len(Hex)
Select Case Mid(Hex, Len(Hex) - i + 1, 1)
Case "0": B = B + 16 ^ (i - 1) * 0
Case "1": B = B + 16 ^ (i - 1) * 1
Case "2": B = B + 16 ^ (i - 1) * 2
Case "3": B = B + 16 ^ (i - 1) * 3
Case "4": B = B + 16 ^ (i - 1) * 4
Case "5": B = B + 16 ^ (i - 1) * 5
Case "6": B = B + 16 ^ (i - 1) * 6
Case "7": B = B + 16 ^ (i - 1) * 7
Case "8": B = B + 16 ^ (i - 1) * 8
Case "9": B = B + 16 ^ (i - 1) * 9
Case "A": B = B + 16 ^ (i - 1) * 10
Case "B": B = B + 16 ^ (i - 1) * 11
Case "C": B = B + 16 ^ (i - 1) * 12
Case "D": B = B + 16 ^ (i - 1) * 13
Case "E": B = B + 16 ^ (i - 1) * 14
Case "F": B = B + 16 ^ (i - 1) * 15
End Select
Next i
HEX_to_DEC = B
End Function
Public Function DEC_to_HEX(Dec As Long) As String
' 用途:将十进制转化为十六进制
' 输入:Dec(十进制数)
' 输入数据类型:Long
' 输出:DEC_to_HEX(十六进制数)
' 输出数据类型:String
Dim a As String
DEC_to_HEX = ""
Do While Dec > 0
a = CStr(Dec Mod 16)
Select Case a
Case "10": a = "A"
Case "11": a = "B"
Case "12": a = "C"
Case "13": a = "D"
Case "14": a = "E"
Case "15": a = "F"
End Select
DEC_to_HEX = a & DEC_to_HEX
Dec = Dec \ 16
Loop
End Function
********************************************************
测试结果正确:
? dec_to_hex(53211)
CFDB
? hex_to_dec("CFDB")
53211
[解决办法]
如果只是long范围的整数 不必这么麻烦吧
Dim a As String
a = 53211
Print a
Print Hex(a)
a = Val("&h" + Hex(a) + "&")
Print a
[解决办法]
你的问题是VB在使用Hex和Val函数处理进制转换,需特别注意整数和长整数之间的不同:
整数用2字节存储数据,而长整数用4字节存储数据.VB的整数所能表示的数值范围在-32768到32767之间.
此时使用Hex和Val函数处理进制转换不存在异议.
Private Sub Command1_Click()
Dim a As Integer
a = -12325
Text1 = Hex(a) 'Text1中显示CFDB
Text2 = Val(&HCFDB) 'Text2中显示-12325
End Sub
当数值大于32767小于65536,必须注意转换的正确性,由16进制转换为10进制时,需在16进制字符串后加"&".
Private Sub Command1_Click()
Dim a As Long
a = 53211
Text1 = Hex(a) 'Text1中显示CFDB
Text2 = Val(&HCFDB&) 'Text2中显示53211
End Sub