Hex to Decimal in C#
Two alternate ways of converting a hex string to decimal
Summary
The other day I needed to write some code to convert an integer expressed in hexadecimal to decimal. I was surprised to find that the way to do it wasn’t the way I expected.
The value I was processing had come from a different environment and had a ‘0x’ prefix to define its base – it was also a string. I just assumed i could feed this to int.Parse and I’d get the answer I was after.
In fact it seems that you either have to get rid of the ‘0x’ prefix or find some other way of doing it. I write a little program to illustrate the choices.
AllowHexSpecifier Weirdness
One thing to notice here which is really quite strange is that the int.Parse option takes an enumerated type argument System.Globalization.NumberStyles.AllowHexSpecifier when in fact it doesn’t allow a Hex specifier ! I’m sure there’s some sense to that but I don’t see it myself !
Example Code
using System; using System.Collections.Generic; using System.Text; using System.Globalization; namespace HexParsing { class Program { static void Main() { string strTestHex ; int iTestHex; string sOut; string s1 = "{0} converted to base 10 using int.Parse is {1}"; string s2 = "{0} converted to base 10 using Convert.ToInt32 is {1}"; //Without a prefix - using int.Parse strTestHex = "7FC3DAE0"; iTestHex = int.Parse( strTestHex, System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture); sOut = String.Format(CultureInfo.CurrentCulture, s1, strTestHex, iTestHex); Console.WriteLine(sOut); //With a prefix - using Convert.ToInt32 strTestHex = "0x7FC3DAE0"; iTestHex = Convert.ToInt32(strTestHex,16); sOut = String.Format(CultureInfo.CurrentCulture, s2, strTestHex, iTestHex); Console.WriteLine(sOut); Console.WriteLine("Press ENTER to close window"); Console.ReadLine(); } } }