UInt32.TryParse() hex-number not working

♀尐吖头ヾ 提交于 2019-11-27 03:53:51

问题


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

32
False
wtf=0

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;
            Console.WriteLine(UInt32.TryParse("0x20",
                              NumberStyles.HexNumber, // I've tried also AllowHexSpecifier
                              CultureInfo.InvariantCulture,  // I've also tried CurrentCulture
                              out wtf));
            Console.WriteLine("wtf={0}", wtf);
        }
    }
}

回答1:


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




回答2:


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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2801509/uint32-tryparse-hex-number-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!