convert HEX (ASCII) to a DEC int


I get on Arduino Serial a string like "CC", and I need to convert it to a int with decimal value of 0xCC (that is 204).

I found in the Forum, some topics about convert long-long values (convert a big string with hex value, to a very big decimal value), or simply get the hex representation of the ASCII character (like 'C' = 0x43) and this isn't what I want.

Knows someone a function to do the simple conversion ("CC -> 204)?

hexDigit = toupper(hexDigit);
digit = (hexDigit >= 'A') ? hexDigit - 'A' + 10 : hexDigit - '0';

"toupper", range checking and double digit conversion is left as an exercise for the reader.

... or you could leave the exercises for others and use either the strtol() or strtoul() function.

Where's the fun in that?

Works fine!

I figured it was simple like atoi, atof, atol, but I don't knew exactly what to look for.


sscanf() is also an option especially for multiple hex codes in one string.

char s[] = "CC 0D";
int xx; 
int yy;
sscanf(s, "%x %x", &xx, &yy);