Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:


  • Hex: 9F4F4108B0BC1F2E02662669A635B9C
  • Wrong .Net conversion: -8032725318385391486974673232284394596
  • Correct conversion: 13234922614173262479486239732201118620
  • Pad 0s & .Net converts correctly: 0000009F4F4108B0BC1F2E02662669A635B9C
  • .Net Padded 0s conversion: also 13234922614173262479486239732201118620

  • Hex: D0752364CFB600E410619304BE135C
  • Wrong .Net conversion: -246854403100748367549686509950069924
  • Correct conversion: 1082373592684167505354120550330274652
  • .Net padded 0s converts correctly: also 1082373592684167505354120550330274652

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading