Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can any of the .NET Parse methods handle a hex string prefixed with "0x"?

I tried parsing a number with .NET Int64.Parse method, and it won't accept a string like "0x3039", even though that's how you write the constant in C#. The documentation specifically disallows the string to have a "0x" prefix, and a trailing "h" doesn't seem to work either.

To parse a hexadecimal number, I must have to use the System.Globalization.NumberStyles.HexNumber option.

If anyone knows off hand, for certain, that Int64.Parse() cannot accept strings with a "0x" prefix, please let me know.

like image 718
Triynko Avatar asked Jun 02 '10 13:06

Triynko


3 Answers

The documentation gives the expressions for the supported number formats and accordingly neither prefixes nor postfixes are allowed for hexadecimal numbers.

Convert.ToInt32(String, Int32) supports the prefixes 0x and 0X when using base 16.

like image 89
Daniel Brückner Avatar answered Nov 13 '22 03:11

Daniel Brückner


No, it won't accept 0x. There's even an AllowHexSpecifier option, but for some reason that just means the a-f digits and still expects you to strip of the 0x part.

like image 44
Joel Coehoorn Avatar answered Nov 13 '22 04:11

Joel Coehoorn


Sorry for late answer to an old question, but this question was the first one that comes up in search for "[.net] 0x prefix".

Yes, there is at least one set of standard .NET functions that do correctly handle hex strings that start with the "0X" prefix.

As of .NET framework 1.1, the Int64Converter, Int32Converter, Int16Converter, and ByteConverter classes in the System.ComponentModel namespace do accept 0X hexadecimal prefix as part of the string.

try
{
    // get integer value of strValue
    // assuming strValue has already been converted to uppercase e.g. by ToUpper()
    int intValue;
    if (strValue.StartsWith("0X"))
    {
        // support 0x hex prefix
        intValue = (Int16)new System.ComponentModel.Int16Converter().ConvertFromString(strValue);
    }
    else
    {
        // decimal
        intValue = int.Parse(strValue);
    }
}
catch (FormatException)
{
}

MSDN documentation link: https://msdn.microsoft.com/en-us/library/system.componentmodel.int16converter(v=vs.71).aspx

like image 2
MarkU Avatar answered Nov 13 '22 04:11

MarkU