How to Convert HEX to RGB (and RGB to HEX): Color Code Math, CSS Syntax, and Worked Examples

October 25, 202612 min readBy Muhammad Shabbir

Learn how to convert HEX color codes to RGB and RGB to HEX by hand and in CSS. Understand 24-bit TrueColor bytes, 3-digit shorthand, alpha channels, and color tools.

Visual breakdown of converting a 6-digit hex color code into 3 decimal RGB channels alongside CSS syntax and a color swatch

Whether you are styling a website in CSS, inspecting design tokens in Figma, configuring tailwind themes, or writing canvas drawing routines in JavaScript, you constantly encounter color codes. Most design mockups supply colors as 6-character hexadecimal strings such as #3B82F6 or #10B981. However, when you need to manipulate color channels dynamically, create semi-transparent backgrounds with opacity, or feed color matrices into WebGL shaders, you need those same values expressed as decimal RGB (Red, Green, Blue) channels.

At first glance, a string like #3B82F6 might look like an arbitrary alphanumeric hash. In reality, it is a compact, elegant encoding of three distinct numbers. Every two characters represent an independent 8-bit byte that directly controls the intensity of red, green, or blue light emitted by your display pixels.

In this guide, you will learn the exact mathematical principles behind hex to rgb conversion, how to calculate conversions by hand using place-value formulas, how to reverse decimal RGB back into clean hexadecimal strings, how CSS 3-digit shorthand and 8-digit alpha channels work, and how to use the free CoditTools Color Converter Tool for instant, bidirectional color transformation.

24-bit TrueColor diagram showing how a 6-digit hexadecimal color code splits into three independent 8-bit bytes for Red, Green, and Blue
Figure 1: Every 6-character hex code represents three 8-bit channels: Byte 1 is Red, Byte 2 is Green, and Byte 3 is Blue.

Understanding Hexadecimal Color Codes and 24-Bit TrueColor

To understand how to convert a hex color code to RGB, you first need to understand the underlying hardware color model used by modern computer screens: 24-bit TrueColor.

Every pixel on your monitor or phone screen is composed of three microscopic sub-pixels: one red, one green, and one blue. By varying the electrical intensity of these three light sources from completely dark (0% light) to maximum brightness (100% light), your screen can reproduce over 16.7 million distinct hues through additive color mixing.

The 8-Bit Channel Architecture

In digital imaging systems, the brightness of each color channel is stored as a single 8-bit byte. An 8-bit binary number can represent $2^8 = 256$ possible values, spanning from 0 (completely off) to 255 (maximum intensity):

  • Red Channel: 8 bits (values 0 to 255)
  • Green Channel: 8 bits (values 0 to 255)
  • Blue Channel: 8 bits (values 0 to 255)

When you combine all three channels ($8 + 8 + 8 = 24$ bits), you get $256 imes 256 imes 256 = 16,777,216$ total color permutations. This is why standard web imaging is referred to as 24-bit TrueColor.

Why Use Hexadecimal Instead of Decimal?

Computers process binary bits (0 and 1). Humans find long binary strings like 001110111000001011110110 unreadable. Decimal notation (e.g., rgb(59, 130, 246)) is friendly to read, but numbers vary in length between 1 and 3 digits, making them clunky in fixed-width code.

Hexadecimal (Base-16) provides the perfect bridge. Because $16 = 2^4$, a single hexadecimal digit represents exactly 4 binary bits (known as a nibble). Consequently, exactly two hexadecimal digits represent an 8-bit byte ($16 imes 16 = 256$ values). A full 24-bit color can always be expressed in exactly six characters, preceded by a hash symbol (#):

Hex Character Decimal Value 4-Bit Binary Hex Character Decimal Value 4-Bit Binary
0 0 0000 8 8 1000
1 1 0001 9 9 1001
2 2 0010 A 10 1010
3 3 0011 B 11 1011
4 4 0100 C 12 1100
5 5 0101 D 13 1101
6 6 0110 E 14 1110
7 7 0111 F 15 1111

When you read a hex code like #RRGGBB, the first two characters (RR) define the Red byte, the middle two (GG) define Green, and the last two (BB) define Blue. If you want a deeper dive into general base arithmetic, see our companion guide on How to Convert Hex, Binary, and Decimal by Hand.

How to Convert HEX to RGB by Hand: Step-by-Step Formula

Converting any 6-digit hex color code into its decimal RGB equivalent requires just one simple mathematical formula applied to each two-character pair.

Mathematical formula diagram showing the place-value multiplication for HEX to RGB and division-by-16 for RGB to HEX
Figure 2: Place-value multiplication converts hex pairs to decimal integers; integer division by 16 reverses the operation.

The Place-Value Conversion Formula

In Base-16, the rightmost digit represents the 1s place ($16^0 = 1$), and the leftmost digit represents the 16s place ($16^1 = 16$). For any two-digit hex pair $D_1 D_2$, the decimal value is calculated as:

ext{Decimal Value} = (D_1 imes 16) + D_2

Remember to substitute letters with their numeric equivalents: $ ext{A}=10$, $ ext{B}=11$, $ ext{C}=12$, $ ext{D}=13$, $ ext{E}=14$, $ ext{F}=15$.

Worked Example 1: Converting #3B82F6 (Tailwind Blue 500)

Let us convert the popular web accent color #3B82F6 into its CSS RGB representation:

  1. Split into pairs: Red = 3B, Green = 82, Blue = F6.
  2. Calculate Red (3B):
    The first digit is 3. The second digit is B, which equals 11.
    $ ext{Red} = (3 imes 16) + 11 = 48 + 11 = 59$.
  3. Calculate Green (82):
    The first digit is 8. The second digit is 2.
    $ ext{Green} = (8 imes 16) + 2 = 128 + 2 = 130$.
  4. Calculate Blue (F6):
    The first digit is F (which equals 15). The second digit is 6.
    $ ext{Blue} = (15 imes 16) + 6 = 240 + 6 = 246$.

Combine the three results into standard CSS functional notation: rgb(59, 130, 246).

Worked Example 2: Converting #10B981 (Emerald Green)

Consider the emerald green shade #10B981:

  • Red (10): $(1 imes 16) + 0 = 16 + 0 = mathbf{16}$.
  • Green (B9): $ ext{B}$ is 11. $(11 imes 16) + 9 = 176 + 9 = mathbf{185}$.
  • Blue (81): $(8 imes 16) + 1 = 128 + 1 = mathbf{129}$.

Resulting CSS value: rgb(16, 185, 129).

Worked Example 3: Converting #EF4444 (Vibrant Red)

Consider the error red tone #EF4444:

  • Red (EF): $ ext{E}$ is 14, $ ext{F}$ is 15. $(14 imes 16) + 15 = 224 + 15 = mathbf{239}$.
  • Green (44): $(4 imes 16) + 4 = 64 + 4 = mathbf{68}$.
  • Blue (44): $(4 imes 16) + 4 = 64 + 4 = mathbf{68}$.

Resulting CSS value: rgb(239, 68, 68).

How to Convert RGB Back to HEX (Reverse Division Method)

When you have decimal RGB values—perhaps generated dynamically by a color picker or extracted from an image—you often need to convert them back into a clean hexadecimal string. The reverse conversion uses integer division by 16.

The Division-by-16 Algorithm

For each color channel value (from 0 to 255):

  1. Divide the number by 16 to find the whole integer quotient: $D_1 = lfloor ext{Value} div 16 floor$.
  2. Find the remainder (modulo): $D_2 = ext{Value} pmod{16}$.
  3. Convert both $D_1$ and $D_2$ into their corresponding hexadecimal digits (0–9 or A–F).
  4. Write the two characters side by side: $D_1 D_2$. If the quotient is 0, preserve the leading zero (e.g., 0A).

Worked Example: Reversing rgb(59, 130, 246) back to HEX

  • Red Channel (59):
    $59 div 16 = 3$ with a remainder of $11$.
    The quotient 3 remains 3. The remainder 11 translates to the hex letter B.
    Red hex pair = 3B.
  • Green Channel (130):
    $130 div 16 = 8$ with a remainder of $2$.
    The quotient 8 remains 8. The remainder 2 remains 2.
    Green hex pair = 82.
  • Blue Channel (246):
    $246 div 16 = 15$ with a remainder of $6$.
    The quotient 15 translates to F. The remainder 6 remains 6.
    Blue hex pair = F6.

Prepend the hash mark: #3B82F6. The conversion roundtrip is complete and mathematically exact.

3-Digit CSS Shorthand and 8-Digit Alpha Channels

Modern web standards include two important variations of the standard 6-digit hex code: 3-digit shorthand notation and 8-digit hexadecimal colors with transparency.

Diagram explaining 3-digit CSS shorthand expansion and 8-digit hexadecimal alpha opacity calculations
Figure 3: CSS expands 3-digit hex by duplicating each character; 8-digit hex appends a two-character alpha transparency byte.

How 3-Digit CSS Shorthand Works (#RGB)

In CSS stylesheets, you will often encounter 3-character hex codes like #FFF, #000, #F0C, or #38F. A very common misconception among beginners is that CSS expands shorthand by appending zeros to the end (e.g., thinking #F0C expands to #F0C000). That is completely incorrect.

The CSS specification dictates that each character is duplicated:

# ext{RGB} implies # ext{RRGGBB}
  • #F0C expands to #FF00CC. In RGB: $ ext{FF}=255$, $ ext{00}=0$, $ ext{CC}=204 implies mathbf{rgb(255, 0, 204)}$.
  • #38F expands to #3388FF. In RGB: $ ext{33}=51$, $ ext{88}=136$, $ ext{FF}=255 implies mathbf{rgb(51, 136, 255)}$.
  • #FA0 expands to #FFAA00. In RGB: $ ext{FF}=255$, $ ext{AA}=170$, $ ext{00}=0 implies mathbf{rgb(255, 170, 0)}$.

Because each character is repeated ($16 imes 16 imes 16$), 3-digit shorthand can only represent $4,096$ colors out of the full 16.7 million palette. It is best reserved for simple primary grays and saturated highlights.

8-Digit Hex Codes with Alpha Transparency (#RRGGBBAA)

Under the CSS Color Module Level 4 specification, browsers support an optional fourth byte appended to hex codes: the alpha channel (opacity). An 8-digit hex code follows the structure #RRGGBBAA.

Like the color channels, the alpha byte AA ranges from 00 ($0$ in decimal, completely invisible) to FF ($255$ in decimal, 100% fully opaque). To find the decimal opacity percentage, divide the alpha byte by 255:

ext{Alpha Decimal (0.0 to 1.0)} = rac{ ext{Decimal Value of } AA}{255}
Opacity Level Hex Alpha Byte Math Calculation Decimal Alpha Example 8-Digit Hex CSS rgba() Equivalent
100% (Opaque) FF $255 div 255$ 1.0 #3B82F6FF rgba(59, 130, 246, 1)
75% Opacity BF / C0 $192 div 255$ 0.75 #3B82F6C0 rgba(59, 130, 246, 0.75)
50% Opacity 80 $128 div 255$ 0.50 #3B82F680 rgba(59, 130, 246, 0.5)
25% Opacity 40 $64 div 255$ 0.25 #3B82F640 rgba(59, 130, 246, 0.25)
10% Opacity 1A $26 div 255$ 0.10 #3B82F61A rgba(59, 130, 246, 0.1)
0% (Transparent) 00 $0 div 255$ 0.0 #3B82F600 rgba(59, 130, 246, 0)

Modern CSS Space-Separated Syntax

Modern CSS allows omitting the traditional comma-separated syntax in favor of clean space-separated values with a slash for opacity: rgb(59 130 246 / 50%). Both modern and legacy rgba() syntaxes produce identical rendering across all modern web browsers.

How to Convert HEX and RGB Using CoditTools Color Converter

While understanding manual calculations is vital for debugging and algorithmic development, manual arithmetic can be tedious when styling entire user interfaces. The CoditTools Color Converter Tool provides a free, lightning-fast browser environment for converting between color spaces in real time.

Four-step interactive workflow of the CoditTools Color Converter tool showing hex input, slider fine-tuning, and 1-click CSS copying
Figure 4: The bidirectional workflow of CoditTools Color Converter: input values, fine-tune sliders, and 1-click copy formatted CSS code.

Step 1: Input Your Color Code

Open the Color Converter Tool. You can enter your color in two convenient ways:

  • Text Input: Type your 6-digit hex code into the input box. The tool automatically handles input with or without the leading # symbol and converts lowercase characters to uppercase.
  • Visual Color Swatch: Click the native color picker box to choose a hue visually from your operating system's color wheel or eyedropper.

Step 2: Fine-Tune with Interactive RGB & HSL Sliders

Unlike basic online converters that only support one-way text conversion, CoditTools provides bidirectional synchronization. Beneath the color swatch, you have independent sliders for Red, Green, and Blue (0 to 255), as well as Hue (0–360°), Saturation (0–100%), and Lightness (0–100%).

Adjusting any slider updates the color swatch, the hex code, and all other channel values simultaneously in real time.

Step 3: Inspect Equivalent Color Spaces

The tool automatically computes the exact mathematical equivalents for four standard imaging color spaces:

  1. HEX: Uppercase 6-character hex code (e.g., #3B82F6).
  2. RGB: Ready-to-paste functional CSS syntax (e.g., rgb(59, 130, 246)).
  3. HSL: Cylindrical coordinate model ideal for designing tints and shades (e.g., hsl(217, 91%, 60%)).
  4. CMYK: Subtractive four-color print process model (e.g., cmyk(76%, 47%, 0%, 4%)).

Step 4: 1-Click Copy Ready for Your Code

Next to each color value, click the Copy button. The tool copies the exact formatted CSS code directly to your clipboard and displays an instant confirmation toast. The entire process runs 100% locally in your browser's JavaScript engine—no network requests are dispatched, ensuring zero latency and complete privacy.

Here is a quick reference table of essential digital design colors, their 24-bit hexadecimal codes, RGB channels, and HSL equivalents:

Color Name Hex Code Red (R) Green (G) Blue (B) CSS RGB String HSL Equivalent
Pure White #FFFFFF 255 255 255 rgb(255, 255, 255) hsl(0, 0%, 100%)
Pure Black #000000 0 0 0 rgb(0, 0, 0) hsl(0, 0%, 0%)
Pure Red #FF0000 255 0 0 rgb(255, 0, 0) hsl(0, 100%, 50%)
Pure Green #00FF00 0 255 0 rgb(0, 255, 0) hsl(120, 100%, 50%)
Pure Blue #0000FF 0 0 255 rgb(0, 0, 255) hsl(240, 100%, 50%)
Emerald Green #10B981 16 185 129 rgb(16, 185, 129) hsl(160, 84%, 39%)
Royal Blue #3B82F6 59 130 246 rgb(59, 130, 246) hsl(217, 91%, 60%)
Vibrant Red #EF4444 239 68 68 rgb(239, 68, 68) hsl(0, 84%, 60%)
Amber / Gold #F59E0B 245 158 11 rgb(245, 158, 11) hsl(38, 92%, 50%)
Indigo / Violet #6366F1 99 102 241 rgb(99, 102, 241) hsl(239, 84%, 67%)
Slate Gray #64748B 100 116 139 rgb(100, 116, 139) hsl(215, 16%, 47%)
Charcoal Dark #1E293B 30 41 59 rgb(30, 41, 59) hsl(217, 33%, 17%)

Common Mistakes When Converting Color Codes and How to Fix Them

When implementing color conversion logic in code or converting values manually, watch out for these frequent pitfalls:

1. Omitting Leading Zeros in Single-Digit Hex Pairs

The Mistake: If an RGB channel evaluates to a number below 16 (for instance, Red = 9), converting $9$ to hexadecimal yields the single character 9. Concatenating raw results like Red=9, Green=130, Blue=246 produces the malformed 5-character string #982F6.

The Fix: Every byte must strictly contain two characters. If the integer division quotient is 0, pad the front with a zero: 09. The valid 6-digit hex code is #0982F6. In JavaScript, always use .padStart(2, "0") on string conversions.

2. Misunderstanding 3-Digit Shorthand Expansion

The Mistake: Assuming that shorthand #123 expands by appending zeros to become #123000. This completely ruins color fidelity.

The Fix: CSS duplicates each character: #123 expands to #112233. In RGB terms: Red is $(1 imes 16) + 1 = 17$, Green is $(2 imes 16) + 2 = 34$, and Blue is $(3 imes 16) + 3 = 51$.

3. Confusing RGB Channel Order with BGR

The Mistake: Certain desktop graphics environments (such as Microsoft Windows GDI bitmaps and the OpenCV computer vision library) store pixels in reverse BGR order rather than RGB order. Reading raw byte buffers directly without swapping can cause blues and reds to appear inverted.

The Fix: Web standards (HTML5 Canvas, CSS, SVG, WebGL) universally mandate RGB byte order: Byte 1 = Red, Byte 2 = Green, Byte 3 = Blue. Verify the expected byte structure of your target framework before parsing binary buffers.

4. Out-of-Bounds Clamping (> 255 or < 0)

The Mistake: Performing dynamic color math (such as brightening or tinting a color by adding an offset) without constraining values. An expression like $240 + 30 = 270$ exceeds the maximum capacity of an 8-bit byte ($255$), producing invalid hex digits like 10E.

The Fix: Always clamp decimal RGB numbers to the strict integer range $[0, 255]$ using Math.min(255, Math.max(0, val)) before converting to hex.

5. Assuming Hex Opacity Follows Decimal Percentages

The Mistake: Assuming that a 50% opacity in 8-digit hex is written as 50 (e.g., writing #3B82F650 to mean 50% opacity).

The Fix: Hex characters represent fractions of 255. In Base-16, $50%$ of $255$ is $127.5$, which rounds to $128$ in decimal. $128$ in hex is 80 ($8 imes 16 = 128$). Therefore, 50% opacity is #3B82F680, whereas writing 50 ($5 imes 16 = 80$) actually produces only $80 div 255 = 31.4%$ opacity.

Frequently Asked Questions

What is the difference between HEX and RGB?

HEX and RGB are two different mathematical representations of the exact same 24-bit TrueColor light values. RGB expresses red, green, and blue light intensity as three separate decimal integers between 0 and 255 (e.g., rgb(59, 130, 246)). HEX condenses those three numbers into a compact 6-character hexadecimal string where each pair of characters represents one color channel (e.g., #3B82F6). Neither format has superior color gamut or visual quality—they describe identical photons on your display.

Can I convert an RGB color with opacity (RGBA) into a HEX code?

Yes. Under the modern CSS Color Module Level 4 standard, you can add an 8-bit alpha channel to the end of a hex code, forming an 8-character string: #RRGGBBAA. To convert an RGBA opacity value between 0.0 and 1.0 into its hex equivalent, multiply the decimal opacity by 255, round to the nearest integer, and convert to a 2-digit hex pair. For example, 50% opacity ($0.50 imes 255 = 128$) becomes 80 in hex, resulting in #3B82F680.

Why do hex color codes only use the letters A through F?

Hexadecimal is a Base-16 numerical system. Standard decimal notation only has ten digits (0 through 9). To represent the values 10, 11, 12, 13, 14, and 15 as single characters, mathematics uses the first six letters of the Latin alphabet: A (10), B (11), C (12), D (13), E (14), and F (15). Letters beyond F are invalid in standard hexadecimal notation.

Does converting between HEX and RGB cause any loss in color quality?

No. Standard 6-digit HEX and 8-bit RGB have a 1-to-1 mathematical mapping. Every integer between 0 and 255 has an exact 2-digit hex pair between 00 and FF, and vice versa. Converting back and forth between HEX and RGB is completely lossless with zero quantization error or color degradation.

What is the modern CSS syntax for RGB colors?

In modern CSS, the commas in the rgb() function are optional. You can specify colors using clean space-separated values, with opacity declared after a forward slash: rgb(59 130 246 / 50%) or rgb(59 130 246 / 0.5). This modern syntax replaces the legacy rgba() function while remaining fully backward-compatible across all current browser rendering engines.

How does 3-digit hex shorthand work in CSS?

CSS expands 3-digit hex codes (#RGB) by repeating each character twice to form a 6-digit code (#RRGGBB). For example, #F0A expands to #FF00AA, which corresponds to rgb(255, 0, 170). It does not append zeros to the end.

Conclusion

Mastering color code conversions bridges the gap between digital design mockups and production web development. Hexadecimal color codes provide a concise, reliable shorthand for stylesheets and design systems, while decimal RGB values give you the programmatic flexibility needed for dynamic alpha blending, animations, and graphic manipulation.

Whenever you need to convert colors by hand, remember the core place-value formula: $(D_1 imes 16) + D_2$. For instant production conversions across CSS HEX, RGB, HSL, and CMYK formats, bookmark the free CoditTools Color Converter Tool. You can also explore our guides on converting hex and binary by hand and free online image formats to master digital asset workflows from code to screen.

Try the tools mentioned in this post - all free, no account needed.

Runs in your browser. No watermarks. No file uploads to a server.

Browse developer tools →