85
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?

0

4 Answers 4

135

Try

Convert.ToUInt32(hex, 16)  //Using ToUInt32 not ToUInt64, as per OP comment
3
  • 5
    Something to keep in mind (although it may not apply to this particular integer conversion)... if the input is bad, Convert.ToUInt32 could be orders of magnitude slower than UInt32.TryParse, like Convert.ToDouble vs Double.TryParse: stackoverflow.com/questions/586436/… Also, it's not always clear what it's converting: stackoverflow.com/questions/586436/…
    – Triynko
    Oct 26, 2011 at 16:43
  • 1
    As @Triynko said, this is a faulty process, as it is liable to throw exceptions. uint.TryParse would be preferable, since it returns a Boolean value indicating success or failure, rather than throwing an exception.
    – Zenexer
    Oct 27, 2012 at 16:57
  • 1
    This approach with Convert.ToUInt32 will handle the '0x' prefix as part of the input.
    – Derek W
    Sep 22, 2015 at 17:05
53

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.

3
  • 22
    Personally, I'd call this behavior a bug. Why on earth would they call the flag AllowHexSpecifier if it doesn't actually allow any hex specifier?
    – Tom Lint
    Oct 8, 2014 at 8:21
  • Keep in mind that there are at least two common hex specifiers out there: 0x and &H Apr 6, 2016 at 13:24
  • just found another potential representation: '#0000103A3C..' Jun 15, 2016 at 16:54
16

Or like

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

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

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;
        }
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.