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

后端 未结 4 2011
庸人自扰
庸人自扰 2020-12-05 18:23

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 Syste

相关标签:
4条回答
  • 2020-12-05 18:27

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

    int a = int.Parse("1310530", NumberStyles.AllowHexSpecifier);
    
    0 讨论(0)
  • 2020-12-05 18:41
    int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");
    
    0 讨论(0)
  • 2020-12-05 18:42

    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
    }
    
    0 讨论(0)
  • 2020-12-05 18:42

    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!

    0 讨论(0)
提交回复
热议问题