Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

java - 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);
}
question from:https://stackoverflow.com/questions/6126439/what-does-0xff-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...