Examples (asterisks next to odd behavior):
[Fact]
public void BigInteger_ToString_behavior_is_odd()
{
writeHex(new BigInteger(short.MaxValue)); // 7fff
writeHex(new BigInteger(short.MaxValue) + 1); // 08000 **
writeHex(new BigInteger(ushort.MaxValue)); // 0ffff **
writeHex(new BigInteger(ushort.MaxValue) + 1); // 10000
writeHex(new BigInteger(int.MaxValue)); // 7fffffff
writeHex(new BigInteger(int.MaxValue) + 1); // 080000000 **
writeHex(new BigInteger(uint.MaxValue)); // 0ffffffff **
writeHex(new BigInteger(uint.MaxValue) + 1); // 100000000
writeHex(new BigInteger(long.MaxValue)); // 7fffffffffffffff
writeHex(new BigInteger(long.MaxValue) + 1); // 08000000000000000 **
writeHex(new BigInteger(ulong.MaxValue)); // 0ffffffffffffffff **
writeHex(new BigInteger(ulong.MaxValue) + 1); // 10000000000000000
}
private static void writeHex(BigInteger value)
{
Console.WriteLine(value.ToString("x"));
}
Without a leading zero, the number may appear as though it is a negative number of the same number of bits in two's complement. Putting a leading zero ensures that the high bit isn't set, so it can't possibly be interpreted as a negative number.
Go ahead and remove the first character, if it's a zero, unless it's the only character in the string.
From my part not sure why this is done, but as you mentioned converting to string and then removing leading zero should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With