Estonian555
Estonian555

Reputation: 25

C# byte array calculation with BigInteger not working properly

So, i need to calculate byte arrays in my program and i noticed weird thing:

        string aaa = "F8F9FAFBFCFD";
        string aaaah = "10101010101";
        BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber) + BigInteger.Parse(aaaah, NumberStyles.HexNumber);
        MessageBox.Show(dsa.ToString("X"));

When i add aaa + aaah, it displays me 9FAFBFCFDFE, but it should display F9FAFBFCFDFE, but when i subtract it does it right, aaa - aaah, displays F7F8F9FAFBFC, everything should be right in my code.

Upvotes: 1

Views: 61

Answers (1)

Phil Ross
Phil Ross

Reputation: 26100

BigInteger.Parse interprets "F8F9FAFBFCFD" as the negative number -7,722,435,347,203 (using two's complement) and not 273,752,541,363,453 as you were probably expecting.

From the documentation for BigInteger.Parse:

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 get the result you are expecting, prefix aaa with a 0 to force it to be interpreted as a positive value:

string aaa = "0F8F9FAFBFCFD";
string aaaah = "10101010101";
BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber)
               + BigInteger.Parse(aaaah, NumberStyles.HexNumber);
MessageBox.Show(dsa.ToString("X")); // outputs 0F9FAFBFCFDFE

Upvotes: 1

Related Questions