Hexadecimal
Example
const toHex = (r, g, b) =>
'#' + [r, g, b].map((n) => n.toString(16)).join('');
toHex(255, 0, 8); // '#ff08'const toHex = (r, g, b) =>
'#' + [r, g, b].map((n) => n.toString(16).padStart(2, '0')).join('');
toHex(255, 0, 8); // '#ff0008'Padding each channel to two hex digits keeps the color six characters long.
Common mistakes
- Converting RGB to hex without padding, so 8 becomes '8' instead of '08' and the color is broken.
Key points
- Each byte converted to hex is padded to two digits with
padStart(2, '0'). - Hex strings are parsed with
parseInt(str, 16);Number(str)needs a0xprefix.
Interview questions
How many bits is one hex digit?
Four. One hex digit covers values 0 to 15, so two digits describe one byte (0 to 255).
What does an 8-digit hex color mean in CSS?
The last two digits are alpha: #00000080 is black at about 50% opacity.