Adding two hex numbers

I am trying to add two hex numbers "920001A" "920001F"

BigInteger number1 = BigInteger.Parse("920001A", NumberStyles.HexNumber);
BigInteger number2 = BigInteger.Parse("920001F", NumberStyles.HexNumber);
BigInteger sum = BigInteger.Add(number1, number2);
MessageBox.Show(sum.ToString("X"));

However output should be "12400039" but its coming "F2400039"

Jon Skeet
people
quotationmark

Both number1 and number2 are negative, as per the documentation:

If value is a hexadecimal string, the Parse(String, NumberStyles) method interprets value as a negative number stored by using two's complement representation if its first two hexadecimal digits are greater than or equal to 0x80. In other words, the method interprets the highest-order bit of the first byte in value as the sign bit. To make sure that a hexadecimal string is correctly interpreted as a positive number, the first digit in value must have a value of zero.

The result is negative (which you'll see if you print the decimal value). It's formatted as F2400039 for the same reason that the input is parsed as a negative number, although I haven't found documentation supporting that yet.

As per the documentation, just add a leading zero when parsing:

BigInteger number1 = BigInteger.Parse("0920001A", NumberStyles.HexNumber);
BigInteger number2 = BigInteger.Parse("0920001F", NumberStyles.HexNumber);

You'll then get the correct result.

people

See more on this question at Stackoverflow