大数的十进制到二进制(> 2253483438943167)

时间:2013-11-08 00:22:52

标签: vb.net

我有一个VB.Net应用程序,它通过一系列进程来解码一个字符串,这个问题就是我找到了一个从二进制转换为十进制的函数,但我找不到一个函数将提供的数字(字符串格式)转换为二进制字符串。作为参考,二进制到十进制转换函数如下:

Public Function baseconv(d As String)
    Dim N As Long
    Dim Res As Long
    For N = Len(d) To 1 Step -1
        Res = Res + ((2 ^ (Len(d) - N)) * CLng(Mid(d, N, 1)))
    Next N
    Return Str(Res)
End Function

4 个答案:

答案 0 :(得分:1)

这是怎么回事?

Module Module1

Sub Main()
    Console.WriteLine(Convert.ToString(2253483438943167 * 5, 2))
    Console.ReadKey()
End Sub

End Module

答案 1 :(得分:1)

如果数字小于16 * 1e18< - >,我会怎么做可以保留在Uint64中:
1)将数字存储在无符号的64位整数内:num。
2)然后在每个位上循环测试它:

 mask = 1<<63
 do
     if ( num AND mask ) then ->> push("1")
     else ->> push("0")
     mask = mask >> 1
 until mask = 0

(其中push使用字符串连接构建输出,或者,如果性能很重要,则使用StringBuilder,或者它可以是流,...)

答案 2 :(得分:1)

尝试使用System.Numerics.BigInteger类,如下所示:

Dim d As String
d = "2253483438943167"

Dim bi As BigInteger
bi = BigInteger.Parse(d)

Dim ba() As Byte
ba = bi.ToByteArray()

Dim s As String
Dim N As Long

Dim pad as Char
pad = "0"c

For N = Len(ba) To 1 Step -1
    s = s + Convert.ToString(ba(N)).PadLeft(8, pad)  
Next N

答案 3 :(得分:1)

怎么样

    Dim foo As BigInteger = Long.MaxValue
    foo += Long.MaxValue
    foo += 2
    Dim s As New System.Text.StringBuilder
    For Each b As Byte In foo.ToByteArray.Reverse
        s.Append(Convert.ToString(b, 2).PadLeft(8, "0"c))
    Next
    Debug.WriteLine(s.ToString.TrimStart("0"c))
    '10000000000000000000000000000000000000000000000000000000000000000