views:

108

answers:

1

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  A: 

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."

Guffa