Extracting RGB Channels from a Hex Color
Use right shift and AND masking to extract individual red, green, and blue channels from a packed 24-bit hex color value like 0xFF6633.
Detailed Explanation
RGB Channel Extraction with Bitwise Operations
Colors in computer graphics are commonly stored as a single integer with 8 bits per channel. A 24-bit RGB color like 0xFF6633 packs red, green, and blue into one value:
0xFF6633 = 11111111 01100110 00110011
^^^^^^^^ ^^^^^^^^ ^^^^^^^^
Red Green Blue
Extracting Each Channel
Use right shift to move the target byte to the lowest position, then AND with 0xFF to isolate it:
const color = 0xFF6633;
const red = (color >> 16) & 0xFF; // 0xFF = 255
const green = (color >> 8) & 0xFF; // 0x66 = 102
const blue = color & 0xFF; // 0x33 = 51
With Alpha (32-bit ARGB)
For 32-bit colors with an alpha channel (ARGB format):
const color = 0x80FF6633;
const alpha = (color >> 24) & 0xFF; // 0x80 = 128
const red = (color >> 16) & 0xFF; // 0xFF = 255
const green = (color >> 8) & 0xFF; // 0x66 = 102
const blue = color & 0xFF; // 0x33 = 51
Packing Channels Back
Use left shift and OR to recombine channels:
const packed = (red << 16) | (green << 8) | blue;
// With alpha:
const argb = (alpha << 24) | (red << 16) | (green << 8) | blue;
Manipulating Individual Channels
Halve the brightness of red only:
const dimRed = ((red >> 1) << 16) | (green << 8) | blue;
Swap red and blue:
const swapped = (blue << 16) | (green << 8) | red;
Use Case
Canvas and WebGL developers extract individual color channels to apply per-channel effects. When processing pixel data from an HTML5 Canvas ImageData buffer (which stores RGBA bytes), extracting and manipulating channels with bitwise operations is 3-5x faster than parsing CSS color strings. This matters when processing millions of pixels in real-time filters, image adjustments, or procedural texture generation.