And now for ISO STANDARD C... #include <string.h>
#include <errno.h>
#include <ctype.h>
int hex2dec(int c) {
static const char *s = "0123456789ABCDEF";
char *p;
if (p = memchr(s, toupper(c), 16))
return p - s;
else {
errno = EDOM;
return -1;
}
}
Or alternatively... #include <stdlib.h>
int hex2dec(int c) {
char s[2] = {c, '\0'};
return strtol(s, NULL, 16);
}
On invalid input, the first one returns -1 and sets errno to EDOM. On invalid input, the second one returns 0 and, as a POSIX extension, may set errno to EINVAL.