I have a situation where I need to convert a hex string 0x8aaaf200
to a uint32_t
. 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 7fffffff
. I think it may be related to uint32_t
size on different machines.
Does anyone have a suggestion on how to fix it ? I can't change the uin32_t
type usage, as it is part of code written by someone else.
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.