[C] Signed Hexadecimal string to long int function
- by Ben
I am trying to convert a 24bit Hexadecimal string (6 characters) signed in two's complement to a long int in C.
This is the function I have come up with:
long int hex2li (char string[])
{
char *pEnd;
long int result = strtol (string, &pEnd, 16);
if (strcmp (pEnd, "") == 0)
{
if (toupper (string[0]) == 'F')
{
return result - 16777216;
}
else
{
return result;
}
}
return LONG_MIN;
}
Is it valid? Is there a better way of doing this?