'除【2】取余法
'ten=要转换的十进制数。
'radix的值表示进制,如4为四进制,16为十六进制。
'base数组补充十进制以上数制的0-9之外的基数,如十六进制需补充ABCDEF六个基数,满足十六个基数,对于10以下进制,设nothing即可。
Private Function TenTo(ten As Long, radix As Integer, ParamArray base As String()) As String
Dim ToRadix As String = ""
While ten >= radix
Dim quot As Integer = ten Mod radix '求ten的余数,每个余数作为转换结果的一部分。
If quot > 9 Then
ToRadix = base(quot - 10) + ToRadix '拼接每位余数,余数大于9,从base中提取替代的基数。
Else
ToRadix = CStr(quot) + ToRadix '拼接每位余数,余数小于10。
End If
ten = ten \ radix '求整,当前的ten是ten除以进制的商。
End While
If ten > 9 Then
ToRadix = CStr(base(ten - 10)) + ToRadix
Else
ToRadix = CStr(ten) + ToRadix
End If
TenTo = ToRadix
End Function
用法:
Dim hex16 As String
hex16 = TenTo(333, 16, {"A", "B", "C", "D", "E", "F"})
Dim hex2 As String
hex2 = TenTo(333, 16, "A", "B", "C", "D", "E", "F")
Dim four As String
four = TenTo(389, 4) '=12011