HEX to RGB Conversion: How Color Codes Work

HEX Color Code Structure

A HEX color code is a 6-digit hexadecimal number prefixed with #. Each pair of digits represents one color channel: red, green, and blue. The values range from 00 (0) to ff (255).

#RRGGBB
 │ │ │
 │ │ └─ Blue  (00–ff)
 │ └─── Green (00–ff)
 └───── Red   (00–ff)

Example: #ff6600
  FF = 255 (red)
  66 = 102 (green)
  00 = 0   (blue)

The Math Behind Conversion

Each pair of hex digits converts to a decimal value by multiplying the first digit by 16 and adding the second:

// #ff6600 → rgb(255, 102, 0)

// FF = 15 × 16 + 15 = 255
// 66 = 6  × 16 + 6  = 102
// 00 = 0  × 16 + 0  = 0

// JavaScript conversion
function hexToRgb(hex) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return { r, g, b };
}

hexToRgb("#ff6600"); // { r: 255, g: 102, b: 0 }
hexToRgb("#a78bfa"); // { r: 167, g: 139, b: 250 }
HEX PairCalculationDecimal
000 × 16 + 00
ff15 × 16 + 15255
808 × 16 + 0128
a710 × 16 + 7167

3-Digit vs 6-Digit HEX

CSS supports a shorthand 3-digit format where each character is doubled:

#RGB  →  #RRGGBB
#fff  →  #ffffff  (white)
#000  →  #000000  (black)
#f0a  →  #ff00aa  (magenta-ish)
#abc  →  #aabbcc

// In JavaScript, expand 3-digit hex
function expandHex(hex) {
  if (hex.length === 4) {
    return '#' + hex[1]+hex[1] + hex[2]+hex[2] + hex[3]+hex[3];
  }
  return hex;
}

Tip: 3-digit HEX only works when both digits of a channel are identical. You cannot represent #123456 as a 3-digit code. Use 6-digit HEX for precise colors.

Alpha Channel

An 8-digit HEX code includes an alpha (opacity) value after the RGB pairs. The alpha channel ranges from 00 (fully transparent) to ff (fully opaque).

#RRGGBBAA

#ff660080  →  rgb(255, 102, 0) at 50% opacity
#00000000  →  fully transparent black
#ffffffcc  →  white at 80% opacity

// CSS usage
.box {
  background: #a78bfa80; /* purple at 50% */
}

Convert HEX to RGB instantly?

Try Color Converter