How to parse hex values ​​in uint?

uint color; bool parsedhex = uint.TryParse(TextBox1.Text, out color); //where Text is of the form 0xFF0000 if(parsedhex) //... 

does not work. What am I doing wrong?

+60
c #
Sep 19 '08 at 1:12
source share
4 answers

Try

 Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment 
+101
Sep 19 '08 at 1:14
source share

You can use the overloaded TryParse() , which adds the NumberStyle parameter to the TryParse call, which provides parsing of hexadecimal values. Use NumberStyles.HexNumber , which allows you to pass a string as a hexadecimal number.

Note The problem with NumberStyles.HexNumber is that it does not support parsing values ​​with a prefix (i.e. 0x , &H or # ), so you have to disable it before trying to parse the value.

Basically you would 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

+38
Sep 19 '08 at 1:19
source share

Or how

 string hexNum = "0xFFFF"; string hexNumWithoutPrefix = hexNum.Substring(2); uint i; bool success = uint.TryParse(hexNumWithoutPrefix, System.Globalization.NumberStyles.HexNumber, null, out i); 
+9
Sep 19 '08 at 1:18
source share

Here is a try-parse style function:

  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; } } 
+4
Oct 10 '13 at 17:06
source share



All Articles