如何从0xRRGGBBAA格式十六进制值中提取RGBA分量
Extracting RGBA Components from 0xRRGGBBAA Hex Values
Hey, glad you already have the hang of pulling RGB components from 0xRRGGBB values—extending that to handle the alpha channel is actually super straightforward! The core logic stays the same: we use bitwise shifts and masks to isolate each 8-bit component, since 0xRRGGBBAA is a 32-bit value where every channel (red, green, blue, alpha) takes up exactly 8 bits.
Here's the step-by-step solution:
- Red (RR): Shift the hex value right by 24 bits, then mask with
255(or0xFFin hex) to grab the top 8 bits. - Green (GG): Shift right by 16 bits, then mask with
255to isolate the next set of 8 bits. - Blue (BB): Shift right by 8 bits, mask with
255to get the third 8-bit segment. - Alpha (AA): No shift needed—just mask the original value with
255to pull out the lowest 8 bits.
Example Code:
const hex = 0xFF000080; // Bright red with 50% opacity const r = hex >> 24 & 255; // 255 (0xFF) const g = hex >> 16 & 255; // 0 (0x00) const b = hex >> 8 & 255; // 0 (0x00) const a = hex & 255; // 128 (0x80, which equals 50% alpha)
Quick Note on Readability:
If you find hex notation more intuitive for color work, you can swap 255 with 0xFF—they’re functionally identical, since 255 is the decimal equivalent of 0xFF:
const r = hex >> 24 & 0xFF; const g = hex >> 16 & 0xFF; const b = hex >> 8 & 0xFF; const a = hex & 0xFF;
That’s all there is to it! It’s just a simple extension of the method you already use for RGB-only values.
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

