Search code examples
c#integerhex

Convert a string containing a hexadecimal value starting with "0x" to an integer or long


How can I convert a string value like "0x310530" to an integer value in C#?

I've tried int.TryParse (and even int.TryParse with System.Globalization.NumberStyles.Any) but it does not work.

UPDATE: It seems that Convert.ToInt64 or Convert.ToInt32 work without having to remove the leading "0x":

long hwnd = Convert.ToInt64("0x310530", 16);

The documentation of Convert.ToInt64 Method (String, Int32) says:

"If fromBase is 16, you can prefix the number specified by the value parameter with "0x" or "0X"."

However, I would prefer a method like TryParse that does not raise exceptions.


Solution

  • int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");