Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting rgb color components from integer value

if there is an integer value, eg. 86 then how can i extraact the r,g,b components from this integer value....? I am working on Visual C++ 2008 express edition. Thanks..

like image 661
JAYMIN Avatar asked Dec 10 '22 17:12

JAYMIN


1 Answers

Usually (and I repeat usually, since you don't specify much in your question) a color is packed in a 4-bytes integer with RGBA components.

What you need to do is mask and shift, for example:

int color = 0xRRGGBBAA;

u8 red = (color & 0xFF000000) >> 24;
u8 green = (color & 0x00FF0000) >> 16;
u8 blue = (color & 0x0000FF00) >> 8;

This assumes the kind of encoding I specified, but can be modified according to yours.

EDIT: In your example you spoke about a 0-255 value. It is not clear if components are 2bit sized (4 intensity values per component).

In that case the approach still remains the same but you will have just few colors:

u8 color = 86;

// so you take 2 bits and multiply by 64 to possibly have intensities: 0, 64, 128, 192
u8 red = ((color & 0xC0) >> 6) * 64; 
u8 green = ((color & 0x30) >> 4) * 64;
u8 blue = ((color & 0x0C) >> 2) * 64;

EDIT2: Maybe your colors are indexed with palette, in that case you should have an array that stores the palette itself and the byte you read from the file should be the index of a color stored somewhere else.

like image 103
Jack Avatar answered Jan 09 '23 18:01

Jack