Option Explicit
'2进制转换为10制数
Public Function BinToDec(bin As String) As Long
Dim i As Long
For i = 1 To Len(bin)
BinToDec = BinToDec * 2 + Val(Mid(bin, i, 1))
Next
End Function
'10进制转换为2制数
Public Function DecToBin(dec As Long) As String
DecToBin = ""
Do While dec > 0
DecToBin = (dec Mod 2) & DecToBin
dec = dec / 2
Loop
End Function
'16进制数转换为10进制数
Public Function HexToDec(str2 As String) As Long
Dim i As Long, a As Variant, k As Long
k = 0
For i = Len(str2) - 1 To 0 Step -1
a = Asc(LCase(Mid(str2, Len(str2) - i, 1))) '统一求得各个字符的小写状态下的字符所对应的ASCII值
a = IIf(a >= 48 And a <= 57, a - 48, a - 87)
'0的ASCII码为48,字母a的ASCII码为97,而16进制下的A对应为10进制下的10
'如果a在16进制下为 0 至 9 的数,则-------
'如果a在16进制下为 a 至 f 的数,则-------
k = k + (16 ^ i) * a '累加,就像 12345=1*10^4+2*10^3+3*10^2+4*10^1+5*1^0
Next
HexToDec = k '得到的这个返回值 K 就是转换后的10进制数
End Function
'10进制转换成16进制数
Public Function DecToHex(X As Long) As String
Dim a As String
Dim r As String
Do While X > 0
r = X Mod 16
X = X / 16
r = IIf(r > 9, Chr(Asc(r - 9) + 16), r)
'如果这里不减9,一旦r为11,12,13,14,15时,就只得到 1 的ASCII码值,得到了一个错误的结果。
a = r + a
Loop
DecToHex = a
End Function
'10进制转换为8进制
Public Function DecToOct(dec As Long) As String
DecToOct = ""
Do While dec > 0
DecToOct = (dec Mod 8) & DecToOct
dec = dec / 8
Loop
End Function
'8进制转换为10进制
Public Function OctToDec(str2 As String) As Long
Dim i As Long, a As Variant, k As Long
k = 0
For i = Len(str2) - 1 To 0 Step -1
a = Asc(Mid(str2, Len(str2) - i, 1)) '统一求得各个字符的小写状态下的字符所对应的ASCII值
a = a - 48
k = k + (8 ^ i) * a '累加,就像 12345=1*10^4+2*10^3+3*10^2+4*10^1+5*1^0
Next
OctToDec = k '得到的这个返回值 K 就是转换后的10进制数
End Function
'8进制转换为16进制
Public Function OctToHex(Oct As String) As String
Dim dec As Long
dec = OctToDec(Oct) '8进制转10进制
OctToHex = DecToHex(dec) ' 10进制转16进制
End Function
'8进制转为2进制
Public Function OctToBin(Oct As String) As String
Dim dec As Long
dec = OctToDec(Oct) '8进制转10进制
OctToBin = DecToBin(dec) ' 10进制转2进制
End Function
'16进制转为8进制
Public Function HexToOct(Hex As String) As String
Dim dec As Long
dec = HexToDec(Hex) '16进制转10进制
HexToOct = DecToOct(dec) '10进制转8进制
End Function
'16进制转为2进制
Public Function HexToBin(Hex As String) As String
Dim dec As Long
dec = HexToDec(Hex) '16进制转10进制
HexToBin = DecToBin(dec) '10进制转2进制
End Function
'2进制转化为16进制
Public Function BinToHex(bin As String) As String
Dim dec As Long
dec = BinToDec(bin) '2进制转为10进制
BinToHex = DecToHex(dec) '10进制转为16进制
End Function
'2进制转化为8进制
Public Function BinToOct(bin As String) As String
Dim dec As Long
dec = BinToDec(bin) '2进制转化为10进制
BinToOct = DecToOct(dec) '10进制转化为8进制
End Function