Easy Hex string "0x1234" to integer conversion?

  • Thread starter Thread starter Ed Sutton
  • Start date Start date
E

Ed Sutton

Is there an easy conversion from a hex string, for example "0x1234" to an
int?

I have written my own many times in other languages, I was just wondering if
there might be something already available for doing this.

-Ed
 
Maybe something like this?

System.Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber)

Lars
 
Thanks Lars!
Maybe something like this?

System.Int32.Parse(hexString,
System.Globalization.NumberStyles.HexNumber)

This threw an exception until I read that it did not support the "0x"
prefix.
hexString="55AA00" works great!

Thanks again,

-Ed
 
Is there an easy conversion from a hex string, for example "0x1234" to an
int?

I have written my own many times in other languages, I was just wondering if
there might be something already available for doing this.

-Ed

Ed,

You know, I thought I knew the answer to this, but I cannot figure out
how to do it either. There seems to be nothing in the VS 2003 help
regarding this.

Otis Mukinfus
http://www.otismukinfus.com
 
Is there an easy conversion from a hex string, for example "0x1234" to an
int?

I have written my own many times in other languages, I was just wondering if
there might be something already available for doing this.

-Ed
Here is the answer:
uint i = Convert.ToUInt32("0xabc", 16);

Otis Mukinfus
http://www.otismukinfus.com
 
Thank you Otis. Very good.
Here is the answer:
uint i = Convert.ToUInt32("0xabc", 16);

So now I have two methods to convert a hex string to an int:

1 - The Convert class supports an optional "0x" or "0X" prefix. For
example, it will convert "0x64", "0X64", and "64" to decimal value of 100.
It does not tolerate leading or trailing white-space.

2 - The System.Int32.Parse approach tolerates white-space, but does not
support the "0x" or "0X" prefix. This approach will convert "64", " 64",
and "64 " to decimal value of 100.

So with C#, I can use the Convert class in conjunction with a string Trim.
I no longer have any reason to write my own hexString-to-int functions.

uint i = Convert.ToUInt32(hexString.Trim(), 16);

Thanks again!

-Ed
 
Back
Top