.netparsinghexbiginteger

How do I convert hexidecimal to decimal using C# & BigInt?


I can reproduce this 1 line all the time & I'm thrown off why .Net 8 x64 is converting to a negative decimal. BigIntegers have to be used because of the hex sizes. Conversion URL fact checking .Net BigInteger.Parse

BigInteger.Parse("D0752364CFB600E410619304BE135C", System.Globalization.NumberStyles.HexNumber).ToString()

2 Examples:




& my list goes on with wrong .Net BigInteger.Parse issues. It's that 1 single line involved.

Anyone around with some suggestions?

I have workarounds but I don't like sloppy band-aids


Solution

  • This is the documented behavior:

    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.

    So the method is working as documented, just not the way you'd like it to work. If you want the value to always be interpreted as a positive value, just prepend "0".