How to parse hex values into a uint?

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?


Solution 1:

Try

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

Solution 2:

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 the documentation for TryParse(String, NumberStyles, IFormatProvider, Int32) for an example of how to use the NumberStyles enumeration.

Solution 3:

Or like

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

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