由于某种原因,以下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);
}
}
}
答案 0 :(得分:22)
您需要删除“0x”前缀。请参阅this blog entry
答案 1 :(得分:7)
// 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
}
答案 2 :(得分:2)
摆脱你想要解析的字符串中的前导“0x”。
答案 3 :(得分:1)
另见http://msdn.microsoft.com/en-us/library/kadka85s%28v=VS.100%29.aspx 在页面底部的示例中:
尝试转换'0x8F8C'失败。