Date: 2017apr27
Updated: 2023jul3
Language: C/C+
Keywords: atoi, hexadecimal
Q. C/C++: I 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 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);
}