将万亿数字转换为二进制
Posted
技术标签:
【中文标题】将万亿数字转换为二进制【英文标题】:Convert Trillion number to Binary 【发布时间】:2020-09-11 21:40:47 【问题描述】:在 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
【问题讨论】:
What is the data type where i can store a trillion number?
- docs.microsoft.com/en-us/office/vba/language/reference/…
【参考方案1】:
您将遇到的一个问题是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
【讨论】:
你指的是哪个实现? 两个函数都返回相同的字符串。我用随机值测试了这两个值,并将它们与Decimal to Binary Converter 输出进行了比较,它们匹配。 DecimalToBinary2 返回错误的数字。我尝试了3252027161并返回011000001110101111111111100011001和正确的是1100 0001 1101 0101 1111 1111 0001 1001(前面的一个零)和436196801,返回01100111111111110101010111000001和正确的是1 1001 1111 1111 1101 0101 1100 0001 span> 请注意,由于浮点数的精度有限,这对于大于9,007,199,254,740,990
的整数将失败。 10 位数字不是问题,但未来的读者可能会感兴趣
谢谢@ÉtienneLaneville以上是关于将万亿数字转换为二进制的主要内容,如果未能解决你的问题,请参考以下文章