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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With