简体   繁体   English

C# - 来自字节数组的 BigInteger 与来自 UInt64 的 BigInteger 产生不同的结果

[英]C# - BigInteger from bytes array vs. from UInt64 produces different results

Consider the following code:考虑以下代码:

ulong max = ulong.MaxValue;
byte[] maxBytes = BitConverter.GetBytes(max);

BigInteger a = new BigInteger(max);
BigInteger b = new BigInteger(maxBytes);

Console.WriteLine(a); // 18446744073709551615
Console.WriteLine(b); // -1

Why doesn't creating an instance of BigInteger from a byte[] representation of ulong.MaxValue produce the expected result (18446744073709551615)?为什么从ulong.MaxValuebyte[]表示创建BigInteger的实例不会产生预期的结果(18446744073709551615)?

BigInteger is signed , and ulong is not. BigInteger 是有符号的,而 ulong 不是。

Because ulong is not signed, it's max value in bytes is all ones, but for signed values the most significant bit indicates polarity.因为 ulong 没有符号,所以它的最大值(以字节为单位)全为 1,但对于有符号值,最高有效位表示极性。

When you use ulong to construct, BigInteger can see the value and use it, but when you pass it as a byte array the SIGNED interpretation of an all ones byte array is negative one.当您使用 ulong 构造时,BigInteger 可以看到该值并使用它,但是当您将其作为字节数组传递时,全字节数组的 SIGNED 解释为负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM