使用 BigInteger 的 C# 字节数组计算无法正常工作
C# byte array calculation with BigInteger not working properly
所以,我需要在我的程序中计算字节数组,我注意到了一些奇怪的事情:
string aaa = "F8F9FAFBFCFD";
string aaaah = "10101010101";
BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber) + BigInteger.Parse(aaaah, NumberStyles.HexNumber);
MessageBox.Show(dsa.ToString("X"));
当我添加 aaa + aaah 时,它显示 9FAFBFCFDFE,但它应该显示 F9FAFBFCFDFE,但是当我减去它时它正确,aaa - aaah,显示 F7F8F9FAFBFC,我的代码中的一切都应该是正确的。
BigInteger.Parse
将 "F8F9FAFBFCFD"
解释为负数 -7,722,435,347,203(使用补码)而不是您可能期望的 273,752,541,363,453。
来自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.
要获得您期望的结果,请在 aaa
前加上 0 以强制将其解释为正值:
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
所以,我需要在我的程序中计算字节数组,我注意到了一些奇怪的事情:
string aaa = "F8F9FAFBFCFD";
string aaaah = "10101010101";
BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber) + BigInteger.Parse(aaaah, NumberStyles.HexNumber);
MessageBox.Show(dsa.ToString("X"));
当我添加 aaa + aaah 时,它显示 9FAFBFCFDFE,但它应该显示 F9FAFBFCFDFE,但是当我减去它时它正确,aaa - aaah,显示 F7F8F9FAFBFC,我的代码中的一切都应该是正确的。
BigInteger.Parse
将 "F8F9FAFBFCFD"
解释为负数 -7,722,435,347,203(使用补码)而不是您可能期望的 273,752,541,363,453。
来自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.
要获得您期望的结果,请在 aaa
前加上 0 以强制将其解释为正值:
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