Skip to content

Technology

How to Convert HEX to RGB (And Why Designers Need Both)

Learn the math behind HEX to RGB color conversion. Understand when to use each format and how to convert between them manually or with formulas.

OurDailyCalc Team 4 min read

In the digital world, every color you see on your monitor, smartphone, or television is synthesized using just three primary colors of light: Red, Green, and Blue (RGB). The way we instruct a computer to mix these lights determines the final color rendered on the screen. The two most ubiquitous methods for declaring these values in web development and design are the RGB function and the Hexadecimal (HEX) color code.

While they look completely different to the human eye, they are mathematically identical representations of the same underlying data. This exhaustive guide will break down the deep domain theory behind color spaces, the mathematics of base-16 conversions, the science of relative luminance, gamma correction, perceptual color models, and provide a comprehensive FAQ on using HEX and RGB effectively.

The Theory of Additive Color and the sRGB Color Space

To understand why HEX and RGB exist, we must first understand the physics of digital displays. Digital screens use an additive color model. Unlike physical paint (which uses a subtractive model where mixing all colors results in black), digital screens emit light. When you mix 100% Red, 100% Green, and 100% Blue light, you get pure, bright White. When all lights are turned off (0%), you get absolute Black.

The standard color space for the web is sRGB (Standard Red Green Blue), created jointly by HP and Microsoft in 1996 and later standardized as IEC 61966-2-1. The sRGB space maps the intensity of each color channel to an 8-bit integer, and critically, it defines a specific gamma curve that governs how encoded values relate to physical light output. This non-linear relationship between numerical value and physical luminance is one of the most commonly misunderstood aspects of digital color.

The Mathematics of 8-Bit Color

An 8-bit integer can store $2^8 = 256$ possible discrete values. Since computers count starting from zero, the range of possible intensities for each color channel is $0$ to $255$.

  • $0$ means the light is completely off.
  • $255$ means the light is at maximum intensity.

Because there are three channels (Red, Green, Blue), the total number of colors that can be represented in the standard 24-bit sRGB color space is:

$$ 256 \times 256 \times 256 = 16{,}777{,}216 \text{ colors} $$

This is often referred to as “True Color” or “16 Million Colors,” which historically was considered the upper limit of human color discrimination. Modern wide-gamut displays like Apple Display P3 and the Rec. 2020 standard move beyond sRGB, encoding each channel at 10 or 12 bits per channel ($2^{10} = 1024$ and $2^{12} = 4096$ values respectively), enabling billions of distinct colors with smoother gradients and more vibrant saturations.

What is RGB?

The RGB format is the most literal representation of this additive model. In CSS and digital design, it is written as a function containing three comma-separated base-10 (decimal) integers.

Example: rgb(255, 87, 51)

  • Red channel is set to 255 (Max intensity)
  • Green channel is set to 87 (approximately 34% intensity)
  • Blue channel is set to 51 (approximately 20% intensity)
  • Resulting color: A vibrant, warm orange.

In modern CSS Color Level 4, the syntax has been updated. rgb() and rgba() are now unified, and space-separated values are accepted: rgb(255 87 51) or rgb(255 87 51 / 80%). However, the comma-separated legacy syntax remains universally supported and is still the dominant form in production codebases.

What is HEX?

A Hexadecimal color code is exactly the same information as the RGB code, but formatted into a base-16 numeral system rather than base-10, and concatenated into a single string.

The Hexadecimal System (Base-16)

We use the decimal system (base-10) in everyday life, which uses 10 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. When we need to represent the number ten, we combine symbols to write “10”.

Computers, operating at a binary level (base-2), process data much more efficiently in powers of 2. Hexadecimal (base-16) is a natural fit because $16 = 2^4$, meaning exactly two hexadecimal digits can represent an 8-bit byte (values 0–255) with no wasted space.

Hexadecimal uses 16 symbols. It borrows 0–9 from the decimal system and uses the first six letters of the alphabet to represent values 10–15:

HexDecimalBinary
0–90–90000–1001
A101010
B111011
C121100
D131101
E141110
F151111

A standard HEX color code consists of a hash/pound symbol # followed by six hexadecimal characters divided into three pairs: #RRGGBB (Red, Green, Blue).

The Conversion Formula: Deep Mathematics

Converting between Base-16 (HEX) and Base-10 (RGB) is a fundamental computer science concept rooted in positional notation.

HEX to RGB Formula

Every positional numeral system assigns each digit a weight equal to the base raised to the power of that digit’s position. For a two-digit Hex pair $X_1 X_0$ (where $X_1$ is the most significant digit and $X_0$ is the least significant):

$$ \text{Decimal Value} = (X_1 \times 16^1) + (X_0 \times 16^0) $$

Since $16^0 = 1$ and $16^1 = 16$, this simplifies to:

$$ \text{Decimal Value} = (X_1 \times 16) + X_0 $$

Step-by-Step Example: Convert #FF5733 to RGB

  1. Split into pairs: FF, 57, 33
  2. Convert the Red channel (FF):
    • $F = 15$
    • $R = (15 \times 16) + 15$
    • $R = 240 + 15 = \mathbf{255}$
  3. Convert the Green channel (57):
    • $5 = 5$, $7 = 7$
    • $G = (5 \times 16) + 7$
    • $G = 80 + 7 = \mathbf{87}$
  4. Convert the Blue channel (33):
    • $3 = 3$
    • $B = (3 \times 16) + 3$
    • $B = 48 + 3 = \mathbf{51}$

Final Result: rgb(255, 87, 51) — a vivid red-orange.

RGB to HEX Formula

To convert a decimal integer (from 0 to 255) into a two-digit hexadecimal string, we use integer division and the modulo operation:

$$ X_1 = \left\lfloor \frac{\text{Value}}{16} \right\rfloor $$ $$ X_0 = \text{Value} \pmod{16} $$

Both $X_1$ and $X_0$ are then mapped to their hex symbol (0–9 stay as digits, 10–15 become A–F).

Step-by-Step Example: Convert rgb(46, 134, 171) to HEX

  1. Convert Red (46):
    • $X_1 = \lfloor 46 / 16 \rfloor = 2$
    • $X_0 = 46 \pmod{16} = 14 \Rightarrow E$
    • Hex Pair: 2E
  2. Convert Green (134):
    • $X_1 = \lfloor 134 / 16 \rfloor = 8$
    • $X_0 = 134 \pmod{16} = 6$
    • Hex Pair: 86
  3. Convert Blue (171):
    • $X_1 = \lfloor 171 / 16 \rfloor = 10 \Rightarrow A$
    • $X_0 = 171 \pmod{16} = 11 \Rightarrow B$
    • Hex Pair: AB

Final Result: #2E86AB — a muted steel blue.

Verification (Back-convert 2E): $(2 \times 16) + 14 = 32 + 14 = 46$ ✓

Relative Luminance, Gamma Correction, and Accessibility

When designers convert HEX/RGB values, they frequently need to calculate the contrast ratio between text and background to ensure WCAG (Web Content Accessibility Guidelines) compliance. This calculation requires understanding Relative Luminance ($Y$).

Why Luminance Is Not a Simple Average

Human eyes do not perceive red, green, and blue light with equal sensitivity. The CIE photopic luminosity function (the sensitivity curve of the human eye’s cone cells in daylight) shows:

  • Green: We are most sensitive (~72% of luminance perception)
  • Red: Moderately sensitive (~21%)
  • Blue: Least sensitive (~7%)

This is why pure green #00FF00 appears far brighter than pure red #FF0000 or pure blue #0000FF, even though all three have the same maximum channel value of 255.

Gamma Correction and the sRGB Transfer Function

Raw sRGB values are gamma-encoded — they are not linear representations of light intensity. The encoding was designed in the 1990s to compensate for the natural gamma response of CRT phosphors. Before calculating luminance, the sRGB values must be linearized (gamma-decoded).

Given a normalized sRGB channel value $C_s = \frac{C_{srgb}}{255} \in [0, 1]$, the linear light value $C_{linear}$ is computed using the piecewise sRGB transfer function:

$$ C_{linear} = \begin{cases} \dfrac{C_s}{12.92}, & \text{if } C_s \le 0.04045 \[8pt] \left( \dfrac{C_s + 0.055}{1.055} \right)^{2.4}, & \text{otherwise} \end{cases} $$

The linear segment (below 0.04045) handles near-black values where the gamma curve would otherwise produce infinite derivatives. The power segment approximates a gamma of approximately 2.2 for the rest of the range.

Computing Relative Luminance

Once $R_{lin}$, $G_{lin}$, and $B_{lin}$ are computed via the above formula, the Relative Luminance $Y$ is:

$$ Y = 0.2126 \cdot R_{lin} + 0.7152 \cdot G_{lin} + 0.0722 \cdot B_{lin} $$

These coefficients (the ITU-R BT.709 primaries) reflect the precise sensitivity of the human visual system to the sRGB red, green, and blue primaries. Their sum equals 1.0, confirming that pure white #FFFFFF has $Y = 1.0$ and pure black #000000 has $Y = 0.0$.

The WCAG Contrast Ratio

The WCAG 2.1 contrast ratio $CR$ between a lighter color ($L_1$, higher $Y$) and a darker color ($L_2$, lower $Y$) is:

$$ CR = \frac{L_1 + 0.05}{L_2 + 0.05} $$

WCAG 2.1 mandates:

  • AA Level: Minimum $CR \geq 4.5:1$ for normal text; $CR \geq 3:1$ for large text (18pt+ or 14pt bold).
  • AAA Level: Minimum $CR \geq 7:1$ for normal text; $CR \geq 4.5:1$ for large text.

Worked Example: Is white text readable on #2E86AB?

  1. Compute $Y$ for #2E86AB (R=46, G=134, B=171):
    • $C_s^R = 46/255 \approx 0.1804$. Since $0.1804 > 0.04045$: $R_{lin} = ((0.1804 + 0.055)/1.055)^{2.4} \approx 0.0476$
    • $C_s^G = 134/255 \approx 0.5255$. $G_{lin} = ((0.5255 + 0.055)/1.055)^{2.4} \approx 0.2384$
    • $C_s^B = 171/255 \approx 0.6706$. $B_{lin} = ((0.6706 + 0.055)/1.055)^{2.4} \approx 0.4090$
    • $Y_{text} = 0.2126 \times 0.0476 + 0.7152 \times 0.2384 + 0.0722 \times 0.4090 \approx 0.010 + 0.170 + 0.030 = \mathbf{0.210}$
  2. For white #FFFFFF: $Y_{white} = 1.0$
  3. $CR = (1.0 + 0.05) / (0.210 + 0.05) = 1.05 / 0.26 \approx \mathbf{4.04:1}$

This just barely fails WCAG AA (requires 4.5:1) for body text, but passes for large text. Switching to a darker shade (e.g., #1A5F7A) would resolve this.

When to Use HEX vs. RGB

While they represent the same data, they serve different purposes in a developer’s workflow.

Why HEX is Ubiquitous

  • Copy & Paste Friendly: HEX is a single, uninterrupted string (e.g., #FF5733). Double-clicking instantly highlights the entire code.
  • Compactness: #F53 (shorthand HEX) is 4 characters. rgb(255,87,51) is 15 characters. HEX saves bytes in CSS stylesheets.
  • Universality: Virtually every design tool (Figma, Photoshop, Sketch, Adobe XD) uses HEX as the primary color reference system.

Why RGB is Still Necessary

  • Opacity (Alpha Channel): The rgba() function allows a fourth parameter for transparency: rgba(255, 87, 51, 0.5) renders the color at 50% opacity. While CSS Level 4 supports 8-digit HEX with alpha (e.g., #FF573380), RGBA notation remains more readable and is universally supported.
  • CSS Animations & Math: When animating colors programmatically, interpolating three separate integer values (0–255) is algorithmically straightforward. Interpolating hex strings requires converting them back to RGB anyway.
  • Dynamic CSS Custom Properties: You can store raw RGB triplets as CSS variables and dynamically compose rgba() calls:
    --brand-rgb: 255, 87, 51;
    background: rgba(var(--brand-rgb), 0.2);
    border-color: rgba(var(--brand-rgb), 1.0);
    This pattern enables a single design token to be used at multiple opacities, something not achievable with bare HEX.

The 3-Digit HEX Shorthand

In CSS, if a 6-digit HEX code is composed of three pairs where both characters in each pair are identical, it can be written as a 3-digit shorthand. The browser interprets #ABC by doubling each character to #AABBCC.

  • #FF0000#F00 (Pure Red)
  • #000000#000 (Black)
  • #FFFFFF#FFF (White)
  • #112233#123

Note that #FF5733 cannot be simplified because 57 and 33 do not have matching internal digits.

Beyond sRGB: HSL, HSB, and Wide-Gamut Color

While HEX and RGB dominate web development, other color models are important for design workflows:

HSL (Hue, Saturation, Lightness)

HSL is a cylindrical transformation of the RGB cube, designed to be more perceptually intuitive. Converting from RGB to HSL:

Let $R’ = R/255$, $G’ = G/255$, $B’ = B/255$, and let $C_{max}$ and $C_{min}$ be the maximum and minimum of these normalized values, with $\Delta = C_{max} - C_{min}$.

The Lightness is: $$ L = \frac{C_{max} + C_{min}}{2} $$

The Saturation is: $$ S = \begin{cases} 0, & \text{if } \Delta = 0 \ \dfrac{\Delta}{1 - |2L - 1|}, & \text{otherwise} \end{cases} $$

The Hue in degrees (0°–360°): $$ H = \begin{cases} 60° \times \left(\dfrac{G’ - B’}{\Delta} \bmod 6\right), & \text{if } C_{max} = R’ \ 60° \times \left(\dfrac{B’ - R’}{\Delta} + 2\right), & \text{if } C_{max} = G’ \ 60° \times \left(\dfrac{R’ - G’}{\Delta} + 4\right), & \text{if } C_{max} = B’ \end{cases} $$

HSL is ideal for generating programmatic color palettes. To lighten a brand color, simply increase $L$; to desaturate it, decrease $S$ — operations that require complex non-linear arithmetic in HEX or RGB.

Comprehensive FAQ

Q: Are there colors that exist in HEX that don’t exist in RGB? A: No. In the sRGB color space, HEX and RGB map 1:1 to the exact same 16.7 million colors. They are perfectly equivalent representations.

Q: What is an 8-digit HEX code? A: CSS Level 4 introduced 8-digit HEX codes to support the Alpha (opacity) channel. The last two digits represent transparency from 00 (0%, fully transparent) to FF (100%, fully opaque). For example, 50% opacity means 128 out of 255, which is 80 in Hex. So #FF573380 is our orange at exactly 50% transparency.

Q: How do CMYK and HEX compare? A: CMYK (Cyan, Magenta, Yellow, Key/Black) is a subtractive color model used for physical printing with ink. HEX is an additive model for screens with light. Converting between them is highly inexact because physical printers cannot reproduce the vibrant neons possible on a backlit screen, and screens struggle to reproduce the deep textural darkness of physical ink.

Q: Why does my HEX color look different on two different monitors? A: HEX codes instruct a monitor on how much electrical signal to send to its pixels. However, the physical hardware of monitors varies wildly in quality, brightness, and color gamut (TN vs. IPS vs. OLED panels). Without hardware color calibration using an ICC profile, #FF5733 will look meaningfully different on an iPhone OLED compared to a budget TN desktop monitor.

Q: Should I use HEX, RGB, or HSL? A: Use HEX for defining static brand tokens — it is concise and copy-paste friendly. Use RGBA when working with legacy opacity configurations or compositing effects. Use HSL when programmatically generating color palettes, because adjusting Lightness is far more intuitive than doing base-16 arithmetic. Use CSS custom properties (variables) to store all three and expose them to your design system.

Q: What is the difference between #FFFFFF (white) and rgb(100%, 100%, 100%)? A: They represent the same color. CSS supports percentage-based RGB syntax — rgb(100%, 100%, 100%) — where each percentage maps linearly to the 0–255 byte range. 100% maps to 255, 50% maps to approximately 127.5 (rounded to 128 by the browser).

Q: What is Lab color space and why would I use it instead of RGB? A: The CIELAB (L*a*b*) color space is perceptually uniform — equal numerical differences in Lab values correspond to equally perceived differences in color. This makes it ideal for tasks like finding the “midpoint” between two colors for accessible UI design, since simple averaging of RGB values does not guarantee a visually equidistant result.

Q: How do I programmatically darken a HEX color by a specific percentage? A: The cleanest approach is to convert HEX → RGB → HSL, reduce the L (Lightness) value by the desired percentage, then convert back: HSL → RGB → HEX. Direct manipulation of HEX or RGB values to darken does not produce perceptually uniform results because the human eye responds non-linearly to changes in raw channel values.

Conclusion

Converting between HEX and RGB is more than just translating numbers; it is the bridge between human-readable design specifications and machine-level light emission instructions. By understanding the underlying base-16 mathematics, the gamma-corrected sRGB color space, relative luminance, WCAG accessibility calculations, and the practical trade-offs between HEX, RGB, and HSL, designers and developers can exert total, pixel-perfect control over their digital interfaces. Use our HEX ↔ RGB Color Converter to instantly perform these calculations and build accessible, beautiful color palettes for any project.

Additional Mathematical & Scientific Context

When utilizing this calculator for personal, professional, or academic purposes, it is essential to understand the underlying mathematical and scientific context that governs the results. Every computational model relies on a specific set of assumptions, boundary conditions, and algorithmic constraints that dictate its accuracy and reliability.

The Role of Precision and Accuracy

In applied mathematics and computational modeling, there is a fundamental distinction between precision and accuracy. Precision refers to the granularity of the numerical output—for instance, returning a result to four decimal places. Accuracy, on the other hand, describes how closely the computed value aligns with the true real-world phenomenon being modeled.

While the algorithms driving this tool are designed for high precision, utilizing standard IEEE 754 floating-point arithmetic for robust calculation, the practical accuracy of the result is heavily dependent on the quality of the input data. Small deviations or estimations in the initial variables can propagate through the mathematical formulas, leading to exponentially magnified variances in the final output—a concept known as sensitivity analysis in numerical methods.

Limitations and Practical Considerations

Furthermore, it is crucial to recognize that no mathematical model can perfectly encapsulate the complexities of the real world. Many formulas employ idealized assumptions, such as linear relationships in inherently non-linear systems, or the exclusion of external variables (like friction, thermodynamic loss, or market volatility) to simplify the calculation process.

Therefore, while the outputs generated by this tool serve as excellent baseline estimates and foundational data points for further analysis, they should not be viewed as absolute certainties. For critical decisions—whether in engineering, finance, health, or logistics—these preliminary calculations should be cross-verified with empirical testing, professional consultation, and rigorous peer-reviewed methodologies. Ultimately, mathematical tools are designed to augment human judgment, not replace it.

Glossary of Key Terms

Understanding the terminology used in these calculations can significantly enhance your ability to interpret the results effectively. Below is a breakdown of core concepts frequently encountered when working with these types of computational models:

  • Variable Input: The independent data points you provide to the formula. Changes in these inputs directly influence the output trajectory.
  • Algorithmic Function: The mathematical ruleset or equation sequence that processes the input variables to produce the final computed result.
  • Margin of Error: The acceptable range of deviation between the calculated estimate and the actual real-world value, often influenced by external unmodeled factors.
  • Base Unit: The standard unit of measurement utilized within the core formula before any final conversions are applied to match user preferences.
  • Constant: A fixed numerical value embedded within the formula that does not change, representing a universally accepted scientific or mathematical standard.
  • Extrapolation: The process of extending the calculated trend beyond the provided data points to predict future outcomes or outliers, which inherently carries a higher degree of uncertainty.
#hex #rgb #color #design
O

Written by OurDailyCalc Team

Subject Matter Expert & Developer

The calculations in this guide have been developed, rigorously tested, and peer-reviewed by the OurDailyCalc engineering team to ensure 100% mathematical accuracy. We build beautiful tools for everyday calculations.