Why does BigInteger.ToString ("x") add 0 for values โ€‹โ€‹between signed.MaxValue (exclusive) and unsigned.MaxValue (inclusive)?

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"));
    }
  • Is there a reason for this?
  • How to remove an extra zero? Can I just check if the string has a zero at the beginning and, if so, delete it? Any corner cases to think about?
+3
source share
6 answers

Without a leading zero, a number may look as if it were a negative number of the same number of bits in two additions. Entering a leading zero ensures that the most significant bit is not set, so it cannot be interpreted as a negative number.

, , .

+3

IMO , , .

, ,

+1

, , , , , .

0

, BigInteger x .

. :

writeHex(new BigInteger(15));

0f

, '0' :

private static void writeHex(BigInteger value)
{
    Console.WriteLine(value.ToString("x").TrimStart('0'));
}

?

, - , , , ToString ( ).

:

StringBuilder builder = new StringBuilder();
byte[] buffer = value.ToByteArray();

// ... A bunch of pre-amble for special cases here,
// though obviously not including the high byte being < 0x10.  Then:

while (index > -1)
{
    builder.Append(buffer[index--].ToString(str, info));
}

Edit

, . , , , , :)

string.TrimStart, .

0

?!

, ! , , ! , .

0

, byte[], ToByteArray, .

So, to answer your question literally, your examples are formatted with a leading zero, because the byte array representing the number contains the leading zero, and this is an array that spits out in hexadecimal format.

0
source

All Articles