Understanding this piece of code (extracting a color component from the whole)

I have a piece of code that I discovered while trying to get pixel values ​​from an image, and I don’t quite understand it,

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

I understand that it adds 1 to the value if there is red, and I think the bit 0x00ff0000is the hexadecimal value for red, and it >>shifts 16 bits to the right.

What is the explanation?

+5
source share
4 answers

This is the extraction of the red component from a number, which (we can assume) represents the color in aRGB.

Firstly:

(rgb & 0x00ff0000)

... rgb, , ( ). 16 ( >> 16), , red.

, , int, :

int color = 0x0012faff;

:

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

18

... hex 0x12 ( color ).

:

int green = (color & 0x0000ff00) >> 8; // 250 = 0xfa
int blue = (color & 0x000000ff); // 255 = 0xff
+10

, 0x00rrggbb, r, g b - .

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

, . , .

+3

rgb , ( 32- int). rgb & 0x00ff0000 , . 16- , red.

+2

& - . a b, a & b 1 , a b . x, x & 1 x x & 0 0.

Therefore, for any integer, I (32 bits long) i & 0x00ff0000will leave only the red component in RGB:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # the RGB value, and
00000000111111110000000000000000 # 0x00ff0000
-------------------------------- # and'ed together, give
00000000xxxxxxxx0000000000000000 # that

There are other ways to extract r, g, and b:

(rgb >> 16) & 0xff # red
(rgb >> 8) & 0xff  # green
rgb & 0xff         # blue
+2
source

All Articles