任意长度的十进制数转为二进制、十六进制,和大数除法算法(只有小半份)

辗转求余法实现的任意长度十进制数到2进制和16进制转换方法


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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Runnerchin/article/details/76022005
个人分类: 代码
想对作者说点什么? 我来说一句

大数的10进制16进制相互转换

2012年11月05日 28KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭