Date: 2017apr27
Update: 2026sep24
Language: C/C++
Keywords: atol, hexadecimal
Q. C/C++: Quickly convert a hex character to an int
A.
inline int xtoi(const int c) {
if (isdigit(c)) {
return c - '0';
}
else if (isxdigit(c)) {
return tolower(c) - 'a' + 10;
}
else {
return -1;
}
}
// Convert 2 adjacent hex characters into an int
inline int xtoi(const int a, const int b) {
return xtoi(a) << 4 | xtoi(b);
}
#if defined(_WIN32) || defined(_WIN64)
// If you're using Windows and want to convert #RRGGBB into COLORREF
COLORREF HtmlToColor(LPCSTR html) {
if (html == NULL) return LIGHT_GRAY;
if (lstrlen(html) != 7) return LIGHT_GRAY;
if (html[0] != '#') return LIGHT_GRAY;
const int red = xtoi(html[1], html[2]);
const int green = xtoi(html[3], html[4]);
const int blue = xtoi(html[5], html[6]);
return RGB(red, green, blue);
}
#endif
Full Example:
#include <stdio.h>
#include <ctype.h>
// (Place above functions here)
int main() {
{ // ONE digit
int c = xtoi('F');
printf("0xF is %d in decimal\n", c);
}
{ // TWO digits
int n = xtoi('F', 'F');
printf("0xFF is %d in decimal\n", n);
}
}
Output:
0xF is 15 in decimal
0xFF is 255 in decimal