Reputation: 42239
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)?
Upvotes: 2
Views: 177
Reputation: 2102
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.
Upvotes: 2