4

我正在将 a 转换byte[]为 aBigInteger并且我想确保它是积极的。文档说

为防止正值被误解为负值,您可以在数组末尾添加一个零字节值。

但它没有具体说明如何。那么,我该怎么做呢?


发现这是最简单的:

public static BigInteger UnsignedBigInt(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
    return new BigInteger(bytes);
}

谢谢 dtb

4

6 回答 6

5

尝试这个:

byte[] bytes = ...

if ((bytes[bytes.Length - 1] & 0x80) != 0)
{
    Array.Resize<byte>(ref bytes, bytes.Length + 1);
}

BigInteger result = new BigInteger(bytes);
于 2012-09-06T03:05:23.973 回答
4

使用静态方法 System.Array.Resize。在你的情况下:

byte[] b = Guid.NewGuid().ToByteArray();
System.Array.Resize<byte>(ref b, b.Length + 1);
b[b.Length - 1] = 0;
于 2012-09-06T03:06:05.183 回答
2
var dest = new byte[17];
Array.Copy(Guid.NewGuid().ToByteArray(), dest , 16);
BigInteger bi = new BigInteger(dest);
于 2012-09-06T03:08:55.330 回答
1

我认为它在页面底部进行了解释。请看示例:


ulong originalNumber = UInt64.MaxValue;
byte[] bytes = BitConverter.GetBytes(originalNumber);
if (originalNumber > 0 && (bytes[bytes.Length - 1] & 0x80) > 0) 
{
   byte[] temp = new byte[bytes.Length];
   Array.Copy(bytes, temp, bytes.Length);
   bytes = new byte[temp.Length + 1];
   Array.Copy(temp, bytes, temp.Length);
}

BigInteger newNumber = new BigInteger(bytes);
Console.WriteLine("Converted the UInt64 value {0:N0} to {1:N0}.", 
                  originalNumber, newNumber);

请注意,此代码是从 MSDN 站点复制的,以显示如何处理在转换为 BigInt 期间可能被视为负数的大数。当谈到效率时,这并不是你能得到的最好的,而且这个线程中提供了更好的片段。

于 2012-09-06T03:01:15.047 回答
1

这看起来非常简单:

var bytesAfter = bytesBefore.Concat(new byte[] { 0 }).ToArray();
于 2012-09-06T03:15:42.927 回答
0

单程:

var x = BigInteger.Abs(new BigInteger(bytes));
于 2012-09-06T03:06:36.297 回答