The math, in one line
A hex color is three bytes written in base 16: two digits for red, two for green, two for blue, each covering 0 to 255. Converting to RGB is just reading those pairs in base 10. #1DB954 splits into 1D, B9, 54, which is 29, 185, 84.
HEX to RGB formula, step by step
Hexadecimal digits run 0 to 9 and then A to F, where A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15. In a two-digit pair the first digit counts sixteens and the second counts ones:
channel = (first digit × 16) + second digit
- Split the code into pairs:
#1DB954gives1D,B9and54. - Red:
1Dis 1 × 16 + 13 = 29. - Green:
B9is 11 × 16 + 9 = 185. - Blue:
54is 5 × 16 + 4 = 84.
The result is rgb(29, 185, 84). Going the other way, divide each channel by 16: the quotient is the first digit and the remainder is the second. The RGB to HEX converter does that direction.
3, 4, 6 and 8 digit hex codes
- 6 digits (
#RRGGBB): the standard form, one pair per channel. - 3 digits (
#RGB): shorthand. Double each digit, so#1B9is#11BB99. - 8 digits (
#RRGGBBAA): the last pair is alpha.80is 128, and 128 ÷ 255 is about 50% opacity, so#1DB95480isrgb(29 185 84 / 50%). - 4 digits (
#RGBA): shorthand for the 8-digit form, doubled the same way.#1B98is#11BB9988.
The converter above takes the 3 and 6 digit forms. For a code with alpha, convert the first six digits and compute the alpha pair separately.
HEX to RGB in code
function hexToRgb(hex: string) {
let h = hex.trim().replace(/^#/, "");
// Expand shorthand: "1B9" -> "11BB99"
if (h.length === 3) h = [...h].map((c) => c + c).join("");
if (!/^[0-9a-f]{6}$/i.test(h)) return null;
return {
r: parseInt(h.slice(0, 2), 16),
g: parseInt(h.slice(2, 4), 16),
b: parseInt(h.slice(4, 6), 16),
};
}
hexToRgb("#1DB954"); // { r: 29, g: 185, b: 84 }Common values
| HEX | RGB | Color |
|---|---|---|
| #FFFFFF | 255, 255, 255 | White |
| #000000 | 0, 0, 0 | Black |
| #FF0000 | 255, 0, 0 | Red |
| #00FF00 | 0, 255, 0 | Green |
| #0000FF | 0, 0, 255 | Blue |
| #FFFF00 | 255, 255, 0 | Yellow |
| #00FFFF | 0, 255, 255 | Cyan |
| #FF00FF | 255, 0, 255 | Magenta |
| #808080 | 128, 128, 128 | Gray |
| #FFA500 | 255, 165, 0 | Orange |
| #3B82F6 | 59, 130, 246 | Tailwind blue-500 |
| #1DB954 | 29, 185, 84 | Spotify green |
Going to print instead?
Hex and RGB both describe light on a screen. Ink needs CMYK, and the conversion is not arithmetic: it depends on paper and press. Use the HEX to CMYK converter, which runs a real ICC profile engine, rather than a formula.
