I need a function to convert a 32bit or 24bit signed (in two's complement) hexadecimal string into a long int. Needs to work on both 32bit and 64bit machines (regardless of the size of long int) and work regardless of whether the machine is a two's complement machine or not.
SOLUTION:
long int hex2li (char hexStr[], int signedHex)
{
int bits = strlen (hexStr) * 4;
char *pEnd;
long long int result = strtoll (hexStr, &pEnd, 16);
if (pEnd[0] == '\0')
{
if (signedHex)
{
if (result >= (1LL << (bits - 1))) result -= (1LL << bits);
}
return (long int) result;
}
return LONG_MIN;
}