BigInteger.Parse () on a hexadecimal number gives negative numbers

I started using the .NET 4 System.Numerics.BigInteger Structure and I ran into a problem.

I am trying to parse a string containing an unsigned hexadecimal number (positive). I get a negative number.

For example, I make the following two statements:

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 statement succeeds; the second statement fails. I actually get -8 instead of 8 in BigInteger .

The problem is that I hex starts with 1 bit, not 0 bits (a digit between 8 and F inclusive). If I add a leading 0, everything will work fine.

Is this a bad use on my part? Is this a bug in BigInteger ?

+4
source share
1 answer

This is exactly what this method should do.

MSDN: BigInteger.Parse method :

“If the value is a hexadecimal string, the Analysis Method (String, NumberStyles) interprets the value as a negative number stored using two paddings 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 as sign bit: To make sure that the correct hexadecimal string is interpreted as a positive number, the first digit in the 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.

+9
source

Source: https://habr.com/ru/post/1311993/


All Articles