ANSI 6x6x6 Color Cube - How to Calculate Color Codes
Learn how the ANSI 216-color cube works with the formula code = 16 + 36*r + 6*g + b. Convert between RGB values and ANSI 256-color codes programmatically.
Detailed Explanation
The 6x6x6 Color Cube
Colors 16-231 in the 256-color palette form a 6x6x6 color cube. Understanding the math behind it lets you programmatically convert between RGB values and ANSI color codes.
The Formula
code = 16 + (36 * r) + (6 * g) + b
Where r, g, and b are indices from 0 to 5, representing these RGB values:
| Index | RGB Value |
|---|---|
| 0 | 0 |
| 1 | 95 |
| 2 | 135 |
| 3 | 175 |
| 4 | 215 |
| 5 | 255 |
Reverse Calculation
To find the RGB values from a color code:
# Python: Convert ANSI code to RGB
def ansi_to_rgb(code):
code -= 16
b = code % 6
g = (code // 6) % 6
r = code // 36
values = [0, 95, 135, 175, 215, 255]
return (values[r], values[g], values[b])
Finding the Nearest 256-Color
When you have an arbitrary RGB value, find the closest match:
def rgb_to_ansi256(r, g, b):
values = [0, 95, 135, 175, 215, 255]
ri = min(range(6), key=lambda i: abs(values[i] - r))
gi = min(range(6), key=lambda i: abs(values[i] - g))
bi = min(range(6), key=lambda i: abs(values[i] - b))
return 16 + (36 * ri) + (6 * gi) + bi
Common Colors in the Cube
| Color | Code | RGB |
|---|---|---|
| Pure Red | 196 | (255, 0, 0) |
| Pure Green | 46 | (0, 255, 0) |
| Pure Blue | 21 | (0, 0, 255) |
| Yellow | 226 | (255, 255, 0) |
| Cyan | 51 | (0, 255, 255) |
| Magenta | 201 | (255, 0, 255) |
| Orange | 208 | (255, 175, 0) |
| Pink | 213 | (255, 135, 255) |
Practical Example
# Print a color gradient across the red axis
for r in 0 1 2 3 4 5; do
code=$((16 + 36 * r))
echo -en "\033[48;5;${code}m \033[0m"
done
echo
Use Case
Understanding the color cube math is critical for developers building terminal color libraries, syntax highlighting engines, or any tool that needs to convert web colors (hex/RGB) to the nearest ANSI 256-color equivalent. Libraries like chalk, colorama, and termcolor use this algorithm internally to provide convenient color APIs.