Reputation: 25
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
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, theParse(String, NumberStyles)
method interpretsvalue
as a negative number stored by using two's complement representation if its first two hexadecimal digits are greater than or equal to0x80
. In other words, the method interprets the highest-order bit of the first byte invalue
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