0

I am working on a small project. During the searching on google I see some code in java .

 int red = (pixel >> 16) & 0x000000FF;

But I do not understand what is the meaning of that ? CAn anybody explain summary of that logical operation ? I read that it is shifted sth like that but shift of what ?

coding_idiot
  • 13,526
  • 10
  • 65
  • 116

3 Answers3

3

The red component of a color is stored as a number between 0-255, but "packed" into an integer. Here's my ASCII art, in binary, 32 bits per integer, showing the 8 bits each for Alpha,Red,Green,and Blue. Read the bit number vertically! I'm numbering from 1, not 0. (Also, you can argue that the numbers go the wrong direction - they are there just to help you count!)

         11111111112222222222333
12345678901234567890123456789012
AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB   the pixel value

The pixel >> 16 will shift the result right by 16 bits. In effect, this removes the G and B stuff

AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB  move everything 16 to the right, this becomes
----------------AAAAAAAARRRRRRRR 

where the - depends on sign. You can look it up but in this case it doesn't matter.

So, you have your Red number, almost. There is still the Alpha component, all that AA.... If you mask ("and") with 0xFF, which is the lowest 8 bits

----------------AAAAAAAARRRRRRRR    (result of the bit shift)
00000000000000000000000011111111    (0xFF)
you get
000000000000000000000000RRRRRRRR

which is the result desired, a number between 0 and 255.

user949300
  • 15,364
  • 7
  • 35
  • 66
1

This is a bitwise "AND" operator. When it is applied to the number FF (hex) it clears all bits of an int except the final 8.

Recall that bitwise "AND" goes through a binary representation of a number, and puts ones in the result only in positions where both operands have ones. Since a 32-bit mask containing FF looks like this in binary

00000000000000000000000011111111

the upper three bytes of the result are going to be zeros. The last byte, where FF has all ones, will be equal to the last byte of the first operand.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

& - bitwise AND operator

>> - right shift operator - shifts a bit pattern to the right

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

For example

4 in binary 100, if you do >>1 that would be 010 which is 2

8 in binary 1000, if you do >>1 that would be 0100 which is 4

See also

What are bitwise shift (bit-shift) operators and how do they work?

Community
  • 1
  • 1
Dhivya
  • 689
  • 8
  • 14