Thursday, April 28, 2011

In C#, How to convert a hexdecimal string to int?

How do I convert the following string:

6F

for example, to a normal int? It's hexdecimal value.

Thanks.

From stackoverflow
  • string s = "6F";
    int i = Int32.Parse(s, NumberStyles.AllowHexSpecifier);
    Console.WriteLine(i); // prints "111" to the console
    

    For details on NumberStyles, see MSDN.

    womp : It would actually be better to use int.Parse, rather than int32.
    Josip Medved : @womp: Why? Both are same type in CLR...
    womp : Just a style recommendation. If you're declaring your variable as "int", then you should use "int.Parse()". If you're using Int32, then use Int32.Parse(). You should really follow a standard usage, whichever one you pick.
    Pop Catalin : @womp, I actually prefer the style Jason used, for some reason it feels more natural it's like saying declare a primitive int and call the method Parse on Int32 class.
  •  int num = Int32.Parse(strValue, System.Globalization.NumberStyles.HexNumber);
    
  • Convert.ToInt32(stringValue,16);

    Where last param is base of 16

0 comments:

Post a Comment