Home » c# » How to parse hex values into a uint?

How to parse hex values into a uint?

Posted by: admin November 29, 2017 Leave a comment

Questions:
uint color; 
bool parsedhex = uint.TryParse(TextBox1.Text, out color); 
//where Text is of the form 0xFF0000
if(parsedhex)
   //...

doesn’t work. What am i doing wrong?

Answers:

Try

Convert.ToUInt32(hex, 16)  //Using ToUInt32 not ToUInt64, as per OP comment

Questions:
Answers:

You can use an overloaded TryParse() which adds a NumberStyle parameter to the TryParse call which provides parsing of Hexadecimal values. Use NumberStyles.HexNumber which allows you to pass the string as a hex number.

Note: The problem with NumberStyles.HexNumber is that it doesn’t support parsing values with a prefix (ie. 0x, &H, or #), so you have to strip it off before trying to parse the value.

Basically you’d do this:

uint color;
var hex = TextBox1.Text;

if (hex.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) ||
    hex.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase)) 
{
    hex = hex.Substring(2);
}

bool parsedSuccessfully = uint.TryParse(hex, 
        NumberStyles.HexNumber, 
        CultureInfo.CurrentCulture, 
        out color);

See this article for an example of how to use the NumberStyles enumeration: http://msdn.microsoft.com/en-us/library/zf50za27.aspx

Questions:
Answers:

Or like

string hexNum = "0xFFFF";
string hexNumWithoutPrefix = hexNum.Substring(2);

uint i;
bool success = uint.TryParse(hexNumWithoutPrefix, System.Globalization.NumberStyles.HexNumber, null, out i);

Questions:
Answers:

Here is a try-parse style function:

    private static bool TryParseHex(string hex, out UInt32 result)
    {
        result = 0;

        if (hex == null)
        {
            return false;
        }

        try
        {
            result = Convert.ToUInt32(hex, 16);

            return true;
        }
        catch (Exception exception)
        {
            return false;
        }
    }