Convert hex string (char []) to int?

kizyle502 picture kizyle502 · Apr 14, 2012 · Viewed 334.9k times · Source

I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.

Answer

user529758 picture user529758 · Apr 14, 2012

Have you tried strtol()?

strtol - convert string to a long integer

Example:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)