Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting an RGB uint into its separate R G B components

I have an RGB colour stored as a uint. I can create this from the RGB values using the bitwise left and bitwise or operator 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?

like image 635
Richard Garside Avatar asked Jan 28 '10 23:01

Richard Garside


2 Answers

r = (colour >> 16) & 0xff;
g = (colour >> 8) & 0xff;
b = colour & 0xff;
like image 125
Paul R Avatar answered Sep 26 '22 08:09

Paul R


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.

like image 20
martin clayton Avatar answered Sep 24 '22 08:09

martin clayton