Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding this piece of code (extracting color component from integer)

Tags:

java

I have a piece of code that I found when trying to get pixel values from an image, and I don't quite understand it,

red = (rgb & 0x00ff0000) >> 16;

I understand that it's adding 1 to the value if red colour is there, and I think the 0x00ff0000 bit is a hexidecimal value for red, and the >> shifts 16 bits to the right.

What is the explanation?

like image 465
Roy James Schumacher Avatar asked Dec 27 '11 00:12

Roy James Schumacher


2 Answers

This is extracting the red component from a number that (one would presume) represents a color in aRGB.

First:

(rgb & 0x00ff0000)

...uses bitwise and to zero all bits of rgb except those from the byte containing the red component (the third most significant byte). Then, that value is shifted right 16 places (using >> 16), so that it occupies the right-most byte, the value of which is then assigned to red.

For example, assume you've got an int representing vivid cyan:

int color = 0x0012faff;

Then, this:

int redOnly = color & 0x00ff0000;
System.out.println(redOnly >> 16);

Prints:

18

...which is the decimal value for hex 0x12 (from the red position in color above).

Similarly, you can get the values of the green and blue components with the following:

int green = (color & 0x0000ff00) >> 8; // 250 = 0xfa
int blue = (color & 0x000000ff); // 255 = 0xff
like image 142
Wayne Avatar answered Nov 10 '22 07:11

Wayne


Let's say you start the operation with value 0x00rrggbb where r, g and b are arbitrary hexadecimal digits. In this case,

0x00rrggbb & 0x00ff0000 -> 0x00rr0000 // bitwise-and operation
0x00rr0000 >> 16        -> 0x000000rr // shift-right operation

In the end, you've got the value of the red component. You can extract other components using similar operations.

like image 21
Eser Aygün Avatar answered Nov 10 '22 07:11

Eser Aygün