Jake Jake - 1 year ago 72
C Question

Hex string conversion using strtol() giving wrong output

I have a situation where I need to convert a hex string

to a
. I first tested it on my local machine (Linux Debian box).

// str contains "0x8aaaf200"

uint32_t var = (uint32_t)strtol(str, NULL, 0);
printf("conversion: %x \n\n", var); // prints 8aaaf200

I then ran it on a different machine (Android based), but to my surprise, the output comes out to be
. I think it may be related to
size on different machines.

Does anyone have a suggestion on how to fix it ? I can't change the
type usage, as it is part of code written by someone else.

Answer Source

You are actually getting LONG_MAX (which is 2147483647 or 0x7FFFFFFF) as return value, which happens when the value passed to strtol is greater than LONG_MAX. You should use the unsigned type to represent that number on your machine. Please use function strtoul() in place of strtol.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download