views:

180

answers:

3

I have an rgb colour stored as an uint. I can create this from the rgb values using the bitwise left and bitwise or opperator in an expression like this:

colour = r<<16 | g<<8 | b;

I want to do the opposite. I have the final number and I want the r, g and b values. Does anyone know how to do this?

+3  A: 

Something like this:

r = ( colour >> 16 ) & 0xFF;
g = ( colour >> 8 )  & 0xFF;
b = colour & 0xFF;

Assuming 8-bit component values. The bitwise-and hex 0xFF masks pick out just the 8-bits for each component.

martin clayton
+3  A: 
r = (colour >> 16) & 0xff;
g = (colour >> 8) & 0xff;
b = colour & 0xff;
Paul R
+3  A: 

You use shift, and then the & operator to mask out unwanted bits:

r = color >> 16;
g = (color >> 8) & 255;
b = color & 255;

Alternatively:

b = color & 255;
color >>= 8;
g = color & 255;
r = color >> 8;
Guffa