How to parse hex values into a uint?

C#

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Try

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

Solution 2 - C#

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 - C#

Or like

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

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

Solution 4 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCameron A. EllisView Question on Stackoverflow
Solution 1 - C#NescioView Answer on Stackoverflow
Solution 2 - C#Jeremy WiebeView Answer on Stackoverflow
Solution 3 - C#Corey RossView Answer on Stackoverflow
Solution 4 - C#Curtis YallopView Answer on Stackoverflow