C# 如何将十六进制值解析为 uint?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/98559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:41:51  来源:igfitidea点击:

How to parse hex values into a uint?

提问by Cameron A. Ellis

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?

不起作用。我究竟做错了什么?

采纳答案by Nescio

Try

尝试

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

回答by Corey Ross

Or like

或者喜欢

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

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

回答by Jeremy Wiebe

You can use an overloaded TryParse()which adds a NumberStyle parameter to the TryParsecall which provides parsing of Hexadecimal values. Use NumberStyles.HexNumberwhich allows you to pass the string as a hex number.

您可以使用重载TryParse()将 NumberStyle 参数添加到TryParse提供十六进制值解析的调用中。使用NumberStyles.HexNumber它允许您将字符串作为十六进制数字传递。

Note: The problem with NumberStyles.HexNumberis that it doesn'tsupport parsing values with a prefix (ie. 0x, &H, or #), so you have to strip it off before trying to parse the value.

注意:问题NumberStyles.HexNumber在于它支持解析带有前缀(即0x, &H, 或#)的值,因此您必须在尝试解析该值之前将其剥离。

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 this article for an example of how to use the NumberStyles enumeration: http://msdn.microsoft.com/en-us/library/zf50za27.aspx

有关如何使用 NumberStyles 枚举的示例,请参阅本文:http: //msdn.microsoft.com/en-us/library/zf50za27.aspx

回答by Curtis Yallop

Here is a try-parse style function:

这是一个 try-parse 风格的函数:

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