1

I've been looking at code from other projects recently seeing if it could give me ideas to pass time, something I noticed is that in some of these projects the & operator is used when setting variables a lot.

For example,

pixels = image.getRGB(0, 0, width, height, null, 0, width);
for (int i = 0; i < pixels.length; i++) {
    pixels[i] = (pixels[i] & 0xff) / 64;
}

or something like,

int x = 64 & 0xff;

What does that & operator do in that context? I've tried finding the answer but seem to come up empty handed, so any help would be much appreciated.

  • this `0xff` is a hexa-decimal value – Blasanka May 30 '17 at 12:12
  • 4
    It's a standard [operator](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html), like `+` or `-`. Your question is similar to asking, "What does the + do in this assignment." – matt May 30 '17 at 12:12
  • It is a bitwise AND. Ex : `101` & `110` = `100`. Convert `64` and `0xff` to binary, do a bitwise AND then try to figure what is the result. It is a convenient way of applying a bitmask. – Arnaud Denoyelle May 30 '17 at 12:13
  • I think I'm going to look more into bitwise operators since it seems I don't have a better understanding of them. Thanks for answering! – MightyChubz May 30 '17 at 12:29
  • "in that context" it is getting the blue component of each pixel - each value returned by getRGB represents the color of a given pixel: 8 bits for alpha (transparency), 8 bits for red, 8 for green and 8 for blue - `& 0xff` clear all bits but the last 8 ones, leaving only the blue component (range 0-255). – user85421 May 30 '17 at 13:31
  • Have you considered reading the Java Tutorial? – Lew Bloch May 30 '17 at 16:33
  • @CarlosHeuberger That's really good explanation! I always had trouble thinking of how that worked. It was a project that had all greyscale textures, the developer made a system to custom set the color of all the textures in runtime. It was actually the fastest renderer in Java I've come across that didn't use OpenGl. The only downside was there was four-color scale support, so only four shades of gray could be used. I may modify it and put it up on GitHub but who knows haha. – MightyChubz May 30 '17 at 16:44
  • @LewBloch I did but for the BITWISE "And" operator it didn't really have anything. After looking a little more through you guys answers and also googling some more I understand how it works. – MightyChubz May 30 '17 at 16:46

0 Answers0