7

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?

4

1 に答える 1

12

それはまさにメソッドが行うべきことです。

MSDN: BigInteger.Parse メソッド:

"値が 16 進文字列の場合、最初の 2 桁の 16 進数が 0x80 以上の場合、Parse(String, NumberStyles) メソッドは、値を 2 の補数表現を使用して格納された負の数として解釈します。つまり、このメソッドは、 value の最初のバイトの最上位ビットを符号ビットとして使用します。16 進文字列が正の数として正しく解釈されるようにするには、value の最初の桁の値が 0 でなければなりません。たとえば、メソッドは 0x80 を次のように解釈します。負の値ですが、0x080 または 0x0080 を正の値として解釈します。」

于 2010-06-06T09:55:18.117 に答える