Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string containing a hexadecimal value starting with "0x" to an integer or long

Tags:

c#

integer

hex

How can I convert a string value like "0x310530" to an integer value in C#?

I've tried int.TryParse (and even int.TryParse with System.Globalization.NumberStyles.Any) but it does not work.

UPDATE: It seems that Convert.ToInt64 or Convert.ToInt32 work without having to remove the leading "0x":

long hwnd = Convert.ToInt64("0x310530", 16); 

The documentation of Convert.ToInt64 Method (String, Int32) says:

"If fromBase is 16, you can prefix the number specified by the value parameter with "0x" or "0X"."

However, I would prefer a method like TryParse that does not raise exceptions.

like image 888
Alex Vang Avatar asked Nov 25 '10 18:11

Alex Vang


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

What is 0x in string?

Indicates that the numeric string represents a hexadecimal value. Valid hexadecimal values include the numeric digits 0-9 and the hexadecimal digits A-F and a-f. Strings that are parsed using this style cannot be prefixed with "0x" or "&h".

Does atoi work for hex?

The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.

How do you read a hex string in Python?

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.


2 Answers

int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530"); 
like image 185
Hans Passant Avatar answered Oct 11 '22 03:10

Hans Passant


From MSDN:

NumberStyles.AllowHexSpecifier

Indicates that the numeric string represents a hexadecimal value. Valid hexadecimal values include the numeric digits 0-9 and the hexadecimal digits A-F and a-f. Strings that are parsed using this style cannot be prefixed with "0x" or "&h".

So you have to strip out the 0x prefix first:

string s = "0x310530"; int result;  if (s != null && s.StartsWith("0x") && int.TryParse(s.Substring(2),                                                     NumberStyles.AllowHexSpecifier,                                                     null,                                                     out result)) {     // result == 3212592 } 
like image 39
dtb Avatar answered Oct 11 '22 03:10

dtb