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"
Method 1: Using maps. The idea is to use a map template to store the mapped values that are hexadecimal to decimal and decimal to hexadecimal. Iterate until one of the given string reaches its length. Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.
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.
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