30

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.

Jimbo
  • 22,379
  • 42
  • 117
  • 159
TechAurelian
  • 5,561
  • 5
  • 50
  • 65

5 Answers5

31
int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This works indeed, thanks. I would still prefer a method like TryParse that does not raise exceptions. – TechAurelian Nov 26 '10 at 17:43
  • 1
    @David: Build a wrapper around it which catches the exception and behaves like TryParse. You could even try some method extension magic if you use C# 3.0 or later. – ZoolWay Apr 14 '11 at 07:32
  • 1
    More on TypeConverter goodness [direct from SHanselman](http://www.hanselman.com/blog/TypeConvertersTheresNotEnoughTypeDescripterGetConverterInTheWorld.aspx) – Cristian Diaconescu Oct 14 '13 at 08:51
17

From MSDN:

NumberStyles.AllowHexSpecifier

Indicates that the numeric string represents a hexadecimal value. Valid hexadecimal values include the numeric digits 0-9 and the hexadecimal digits A-F and a-f. Strings that are parsed using this style cannot be prefixed with "0x" or "&h".

So you have to strip out the 0x prefix first:

string s = "0x310530";
int result;

if (s != null && s.StartsWith("0x") && int.TryParse(s.Substring(2),
                                                    NumberStyles.AllowHexSpecifier,
                                                    null,
                                                    out result))
{
    // result == 3212592
}
Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 5
    Seems like a terrible name then because "0x" and "&H" are common hexadecimal specifiers, and yet they aren't "allowed". Weird. – Dai Nov 13 '19 at 07:01
  • can you please my related [question](https://stackoverflow.com/questions/61857579/converting-string-to-equivalent-hex-in-c-sharp) – Moeez May 17 '20 at 19:37
  • @Dai I think you have to read it as 'Allow the Hex-Specifier / allow that it is specifying a hex value'. – DennisVM-D2i Apr 28 '23 at 17:17
3

Direct from SHanselman, as pointed by Cristi Diaconescu, but I've included the main source code:

public static T GetTfromString<T>(string mystring)
{
   var foo = TypeDescriptor.GetConverter(typeof(T));
   return (T)(foo.ConvertFromInvariantString(mystring));
}

The whole article deserves a closer look!

Community
  • 1
  • 1
Caverna
  • 461
  • 9
  • 16
  • can you please my related [question](https://stackoverflow.com/questions/61857579/converting-string-to-equivalent-hex-in-c-sharp) – Moeez May 17 '20 at 19:39
1

If you remove the leading 0x, you could use int.Parse

int a = int.Parse("1310530", NumberStyles.AllowHexSpecifier);
Orjanp
  • 10,641
  • 12
  • 36
  • 39
0

Building further upon Caverna's answer I added a tryparse method so we can test if a conversion is valid to a certain type.

public static T GetTfromString<T>(string mystring)
{
    var foo = TypeDescriptor.GetConverter(typeof(T));
    return (T)(foo.ConvertFromInvariantString(mystring));
}

public static bool TryGetTFromString<T>(string mystring, out T value)
{
    try
    {
        value = GetTfromString<T>(mystring);
        return true;
    }
    catch (FormatException)
    {
        value = default(T);
        return false;
    }
}
Peter
  • 14,221
  • 15
  • 70
  • 110