将双整数转换为十六进制字符串?抛出异常,为什么?

convert biginteger to hex String? throws exception, why?

我正在尝试将 publickey 变量数组中的数字转换为 Hex 数字。代码 HEX_key = Hex(publickey(0)) 抛出错误:

System.ArgumentException: 'Argument 'Number' cannot be converted to type 'BigInteger'.'

我该如何纠正这个问题?如何将 BigInteger 转换为十六进制字符串?

public key is "-31969172801463260124234214026687674925736772420938592197321821673909885626448"

Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click

     Dim publickey() As BigInteger
    Dim HEX_key As String = Nothing
    publickey = EccMultiply(GENPOINT, Privatekey)
    HEX_key = Hex(publickey(0))
    TextBox11.Text = HEX_key

End Sub

P.S: EccMultiply() 是一个函数,它给出我上面提到的 "-31969172801463260124234214026687674925736772420938592197321821673909885626448" 值,publickey 变量具有该值现在,所以 publickey = (that big number)Function EccMultiply(genpoint, ScalarHex)。我没有在此处包含函数代码,因为它会使代码变长。 Hex()"Imports System.Numerics"

您误解了错误消息。它并不是告诉您参数是一个无法转换为 BigInteger 值的值。它告诉你 Hex 不支持 BigInteger 类型。文档指出带有 Object 参数的重载接受 "Any valid numeric expression or String expression" 但这意味着任何标准数字类型。 Hex 不明白 BigInteger。我认为您最好的选择是将 BigInteger 转换为 Byte 数组,然后自己转换为十六进制。

这是一个扩展方法,可以将 BigInteger 转换为十六进制 String:

Imports System.Numerics
Imports System.Runtime.CompilerServices

Public Module BigIntegerExtensions

    <Extension>
    Public Function ToHexadecimal(source As BigInteger) As String
        Dim data = source.ToByteArray()

        Return String.Concat(data.Reverse().Select(Function(b) b.ToString("X2")))
    End Function

End Module

下面是一些示例用法:

Imports System.Numerics

Module Module1

    Sub Main()
        Dim n = 123456789
        Dim b = New BigInteger(n)

        Console.WriteLine(n.ToString("X"))
        Console.WriteLine(b.ToHexadecimal())

        Console.ReadLine()
    End Sub

End Module

您会注意到,在该示例中,第二个输出具有第一个输出缺少的前导“0”。这是因为每个 Byte 都被转换为两个十六进制数字,因此输出将始终具有偶数个数字。如果你不想那样,那么你可以在输出上调用 TrimStart 或者你可以以不同的方式处理最高位字节:

Imports System.Numerics
Imports System.Runtime.CompilerServices

Public Module BigIntegerExtensions

    <Extension>
    Public Function ToHexadecimal(source As BigInteger) As String
        Dim data = source.ToByteArray()

        Array.Reverse(data)

        Return String.Concat(data.Skip(1).
                                  Select(Function(b) b.ToString("X2")).
                                  Prepend(data(0).ToString("X")))
    End Function

End Module