将万亿数字转换为二进制

问题描述

在VB6中,我试图将数字转换为二进制,但是当数字具有10位数字时,我总是会出现溢出错误。 我可以存储一万亿个数字的数据类型是什么? 这是当数字少于10位时起作用的代码

Public Function DecimalToBinary(DecimalNum As Double) As _
String
Dim tmp As String
Dim n As Double

n = DecimalNum

tmp = Trim(Str(n Mod 2))
n = n \ 2

do while n <> 0
    tmp = Trim(Str(n Mod 2)) & tmp
    n = n \ 2
Loop

DecimalToBinary = tmp
End Function

解决方法

您将遇到的问题之一是Mod运算符将无法使用大于Long(2,147,483,647)的值。您可以按照此答案中的描述重写Mod函数:VBA equivalent to Excel's mod function

' Divide the number by 2.
' Get the integer quotient for the next iteration.
' Get the remainder for the binary digit.
' Repeat the steps until the quotient is equal to 0.
Public Function DecimalToBinary(DecimalNum As Double) As String
    Dim tmp As String
    Dim n As Double
    
    n = DecimalNum
    
    Do While n <> 0
        tmp = Remainder(n,2) & tmp
        n = Int(n / 2)
    Loop
    
    DecimalToBinary = tmp

End Function

Function Remainder(Dividend As Variant,Divisor As Variant) As Variant
    Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function

您也可以重写函数,以完全避免Mod

Public Function DecimalToBinary2(DecimalNum As Double) As String
    Dim tmp As String
    Dim n As Double
    Dim iCounter As Integer
    Dim iBits As Integer
    Dim dblMaxSize As Double
    
    n = DecimalNum
    iBits = 1
    dblMaxSize = 1
    
    ' Get number of bits
    Do While dblMaxSize <= n
        dblMaxSize = dblMaxSize * 2
        iBits = iBits + 1
    Loop

    ' Move back down one bit
    dblMaxSize = dblMaxSize / 2
    iBits = iBits - 1

    ' Work back down bit by bit
    For iCounter = iBits To 1 Step -1
        If n - dblMaxSize >= 0 Then
            tmp = tmp & "1"
            n = n - dblMaxSize
        Else
            ' This bit is too large
            tmp = tmp & "0"
        End If
        dblMaxSize = dblMaxSize / 2
    Next
    
    DecimalToBinary2 = tmp

End Function

此函数查找比您的数字大的位,然后逐位向下计算,以确定是否可以从您的数字中减去每一位的值。这是一种非常基本的方法,但是可以完成工作。

对于这两个函数,如果要将二进制字符串分成8位一组,则可以使用如下函数来填充字符串:

Public Function ConvertToBytes(p_sBits As String)
    Dim iLength As Integer
    Dim iBytes As Integer
    
    iLength = Len(p_sBits)
    If iLength Mod 8 > 0 Then
        iBytes = Int(iLength / 8) + 1
    Else
        iBytes = Int(iLength / 8)
    End If
    
    ConvertToBytes = Right("00000000" & p_sBits,iBytes * 8)

End Function