Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "& 0xff" do?

I am trying to understand the code below where b is a given integer and image is an image.

I understand that if the RGB value at given point i,j is greater than b then set that pixel to white else set to black. so would convert the image into black and white.

However I am lost to what (& 0xff) actually does, I am guessing its a kind of binary shift?

if ((image.getRGB(i, j) & 0xff) > b) {     image.setRGB(i, j, 0xffffff) ; } else {     image.setRGB(i, j, 0x000000); } 
like image 386
Lunar Avatar asked May 25 '11 14:05

Lunar


People also ask

What does the fox say Meaning?

Speaking of the meaning of the song, Vegard characterizes it as coming from "a genuine wonder of what the fox says, because we didn't know". Although interpreted by some commentators as a reference to the furry fandom, the brothers have stated they did not know about its existence when producing "The Fox".

What does the fox say for real?

One of the most common fox vocalizations is a raspy bark. Scientists believe foxes use this barking sound to identify themselves and communicate with other foxes. Another eerie fox vocalization is a type of high-pitched howl that's almost like a scream.

How can I find a song by the sound?

On your phone, touch and hold the Home button or say "Hey Google." Ask "What's this song?" Play a song or hum, whistle, or sing the melody of a song. Hum, whistle, or sing: Google Assistant will identify potential matches for the song.


2 Answers

It's a so-called mask. The thing is, you get the RGB value all in one integer, with one byte for each component. Something like 0xAARRGGBB (alpha, red, green, blue). By performing a bitwise-and with 0xFF, you keep just the last part, which is blue. For other channels, you'd use:

int alpha = (rgb >>> 24) & 0xFF; int red   = (rgb >>> 16) & 0xFF; int green = (rgb >>>  8) & 0xFF; int blue  = (rgb >>>  0) & 0xFF; 

In the alpha case, you can skip & 0xFF, because it doesn't do anything; same for shifting by 0 in the blue case.

like image 152
xs0 Avatar answered Sep 20 '22 19:09

xs0


The

& 0xFF 

is getting one of the color components (either red or blue, I forget which).

If the color mask is not performed, consider RGB (0, 127, 0), and the threshold 63. The getRGB(...) call would return

(0 * 256 * 256) + (127 * 256) + 0 = 32512 

Which is clearly more than the threshold 63. But the intent was to ignore the other two color channels. The bitmask gets only the lowest 8 bits, with is zero.

The

> b 

is checking if the color is brighter than a particular threshold, 'b'.

If the threshold is exceeded, the pixel is colored white, using

image.setRGB(i,j,0xffffff) 

... otherwise it is colored black, using

image.setRGB(i,j,0x000000) 

So it is a conversion to black and white based on a simple pixel-by-pixel threshold on a single color channel.

like image 31
Dilum Ranatunga Avatar answered Sep 18 '22 19:09

Dilum Ranatunga