24

出于某种原因,以下 C# 控制台程序总是输出:

32

wtf=0

我究竟做错了什么?

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

4 回答 4

31

您需要删除“0x”前缀。请参阅此博客条目

于 2010-05-10T09:23:44.040 回答
8
// 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
}
于 2010-08-25T22:06:53.633 回答
2

去掉你试图解析的字符串中的前导“0x”。

于 2010-05-10T09:25:05.050 回答
1

另请参阅http://msdn.microsoft.com/en-us/library/kadka85s%28v=VS.100%29.aspx 在页面底部的示例中:

尝试转换“0x8F8C”失败。

于 2010-05-10T09:26:15.250 回答