Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two hex numbers

Tags:

c#

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"

like image 814
Chetan.B Avatar asked Jan 15 '18 11:01

Chetan.B


People also ask

How do you add two hex strings?

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.


1 Answers

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.

like image 60
Jon Skeet Avatar answered Sep 16 '22 21:09

Jon Skeet