Sub asdf()
Debug.Print Dec2Bin("3214123412351234123415123412351234123451235123412341234")
Debug.Print Dec2Hex("3214123412351234123415123412351234123451235123412341234")
End Sub
 
 
'任意长度的10进制数的整除运算,除数为2
Function Div2(devidend As String) As String
    Dim Remain As Boolean   '当前数位是否有余数
    For i = 1 To Len(devidend)
        Dim CuInt As Integer
        CuInt = IIf(Remain, 10, 0) + Mid(devidend, i, 1) '上一位有余数时,加到当前数位上再做除法
        Remain = Not (CuInt Mod 2 = 0)
        Div2 = Div2 & CuInt \ 2
    Next i
End Function
 
 
'任意长度的10进制数对2求余(判断最后一位数字是奇数还是偶数)
Function Mod2(devidend As String) As Integer
    Mod2 = IIf(Right(devidend, 1) Mod 2 = 1, 1, 0)
End Function
 
 
'任意长度的10进制数转为2进制,辗转求余
Function Dec2Bin(devidend As String) As String
    Dim res As String
    res = devidend
    Do
        Dec2Bin = Mod2(res) & Dec2Bin
        res = Div2(res)
    Loop Until (res = 0)
End Function
 
 
'任意长度的10进制数转为16进制(先转成2进制,再转成16进制)
Function Dec2Hex(devidend As String) As String
    Dim res As String
    res = Dec2Bin(devidend)
    If Len(res) Mod 4 > 0 Then res = String(4 - (Len(res) Mod 4), "0") & res '补齐起始4位
    For i = 1 To Len(res) - 3 Step 4
        Dec2Hex = Dec2Hex & Hex(Mid(res, i, 1) * 8 + Mid(res, i + 1, 1) * 4 + Mid(res, i + 2, 1) * 2 + Mid(res, i + 3, 1))
    Next i
End Function
分类: articles