How to color a mask in c

how do you color mask an unsigned 32 bit integer for red, green and blue values

This is true? (color_to_be_masked → 8)

0


a source to share


4 answers


This will give you the result you want:



short red = (color >> 16) & 0xFF;
short green = (color >> 8) & 0xFF;
short blue = (color) & 0xFF;

      

+2


a source


"It depends", namely which bits are colored.

Often they are displayed "backward" so that red is in the lowest bit, green is in the middle, and blue is on top (sometimes an alpha is used after it if used).

Assuming 8 bits per component, you should:

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 are actually using the "rgba" component order, replace it with the above:

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 offset before I mask, which is nice as it creates a constant that forms a smaller mask which is potentially more efficient.

0


a source


It depends on the format. If you want to keep only the red and the colors are kept at the RGBA edges RRGGBBAA

, then it will color & 0xFF000000

mask all other colors. If you want to know the red value for the same format, (color >> 24) & 0xFF

get it.

0


a source


If after clicking on char or uint8_t, it works as you said.

Otherwise, you need to add as well &0xff

, otherwise you will have the rest of the bits (for all but the most significant color). So, something like (color >> multiple_of_8) &0xff

.

An important detail: there is an order of RGBA and BGRA components, and there are different concepts on different processors. You should know which one you need to do correctly (e.g. Windows GDI - BGRA).

0


a source







All Articles