how do you color mask a 32 bit unsigned integer for the red, green, and blue values
is it like this? (color_to_be_masked>>8)
This should get you the result you want:
short red = (color >> 16) & 0xFF;
short green = (color >> 8) & 0xFF;
short blue = (color) & 0xFF;
It depends on the format. If you only want to keep the red, and the colors are stored nibble-wise RGBA RRGGBBAA
, then color & 0xFF000000
will mask out all the other colors. If you want to know the red value for that same format, (color >> 24) & 0xFF
will get it.
"It depends", namely on which bits are which color.
Often they're mapped "backwards", so that Red is in the lower-most bits, green in the "middle", and blue on top (sometimes followed by alpha, if that is being used).
Assuming 8 bits per component, you would have:
uint32_t abgr = 0x80eeccaa; /* Or whatever. */
const uint8_t red = abgr & 0xff;
const uint8_t green = (abgr >> 8) & 0xff;
const uint8_t blue = (abgr >> 16) & 0xff;
const uint8_t alpha = (abgr >> 24) & 0xff;
If you're really using "rgba" component order, swap the above around:
uint32_t rgba = 0xaaccee80; /* Or whatever. */
const uint8_t red = (abgr >> 24) & 0xff;
const uint8_t green = (abgr >> 16) & 0xff;
const uint8_t blue = (abgr >> 8) & 0xff;
const uint8_t alpha = abgr & 0xff;
Note that I shift before I mask, that's nice since it makes the constant that forms the mask smaller which is potentially more efficient.
If you cast to char or uint8_t afterwards, it works like you said.
Otherwise you need to add a &0xff
as well, or you'll have the remaining bits too (for all but the most significant color). So, something like (color >> multiple_of_8) &0xff
.
Important detail: There is RGBA and BGRA component ordering, and there are different endiannesses on different CPUs. You must know which one you have to get it right (e.g. Windows GDI is BGRA).