简体   繁体   中英

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)?

BigInteger is signed , and ulong is not.

Because ulong is not signed, it's max value in bytes is all ones, but for signed values the most significant bit indicates polarity.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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