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

130 Views Asked by At

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

1

There are 1 best solutions below

0
Chuck On BEST ANSWER

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.