BigInteger.Parse() on hexadecimal number gives negative numbers

為{幸葍}努か 提交于 2019-12-10 14:22:44

问题


I've started using .NET 4 System.Numerics.BigInteger Structure and I've encountered a problem.

I'm trying to parse a string that contains a hexadecimal number with no sign (positive). I'm getting a negative number.

For example, I do the following two asserts:

Assert.IsTrue(System.Int64.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "Int64");
Assert.IsTrue(System.Numerics.BigInteger.Parse("8", NumberStyles.HexNumber, CultureInfo.InvariantCulture) > 0, "BigInteger");

The first assert succeeds, the second assert fails. I actually get -8 instead of 8 in the BigInteger.

The problem seems to be when I'm the hexadecimal starts with 1 bit and not 0 bit (a digit between 8 and F inclusive). If I add a leading 0, everything works perfectly.

Is that a bad usage on my part? Is it a bug in BigInteger?


回答1:


It's exactly what the method is supposed to do.

MSDN: BigInteger.Parse Method:

"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. For example, the method interprets 0x80 as a negative value, but it interprets either 0x080 or 0x0080 as a positive value."



来源:https://stackoverflow.com/questions/2983706/biginteger-parse-on-hexadecimal-number-gives-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!