Take the 2-minute tour ×

For some reason the following C# Console program always outputs:


What am I doing wrong?

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            Console.WriteLine(Convert.ToUInt32("0x20", 16));
            UInt32 wtf = 0;
                              NumberStyles.HexNumber, // I've tried also AllowHexSpecifier
                              CultureInfo.InvariantCulture,  // I've also tried CurrentCulture
                              out wtf));
            Console.WriteLine("wtf={0}", wtf);
share|improve this question
IIRC, Java has the same silliness. –  leppie Jul 20 '11 at 13:05

4 Answers 4

up vote 10 down vote accepted

You need to drop the "0x" prefix. Please see this blog entry

share|improve this answer
You're absolutely right. So, does every C# programmer manually "trim-off" any "0x" (if present) or is there a short-cut? BTW: I'll accept this as solution as soon as SO allows me :-) –  S.C. Madsen May 10 '10 at 9:27
Wow. That's close to a bug I would say. –  kenny May 10 '10 at 9:53
@S.C. Madsen: I think I did "trim-off" "manually" when I needed this functionality in an earlier project. Not pretty, but worked well... –  Peter May 10 '10 at 11:40
Peter: I've gone and done the same in my application. I really think this is a major short-coming of the TryParse() method. –  S.C. Madsen May 10 '10 at 17:54
From NumberStyles Enumeration, AllowHexSpecifier: Strings that are parsed using this style cannot be prefixed with "0x" or "&h". –  DavidRR Sep 11 at 20:25
// stupid but effective way to improve the parsing
char[] _trim_hex = new char[] {'0','x'};
int temp;

if (int.TryParse(value.TrimStart(_trim_hex), NumberStyles.HexNumber, null, out temp))
    // temp is good
share|improve this answer

Get rid of the leading "0x" in the string you're trying to parse.

share|improve this answer

See also http://msdn.microsoft.com/en-us/library/kadka85s%28v=VS.100%29.aspx In the example at the bottom of the page:

Attempted conversion of '0x8F8C' failed.

share|improve this answer

Your Answer


