how to color mask in c

喜夏-厌秋 提交于 2019-12-20 06:11:03

问题


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)


回答1:


This should get you the result you want:

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



回答2:


"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.




回答3:


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.




回答4:


If you cast to char or uint8_t afterwards, it works like you said.

Otherwise you need to add a &0xffas 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).



来源:https://stackoverflow.com/questions/5487373/how-to-color-mask-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!