简体   繁体   中英

having trouble understanding code, specifically the &

I am reading a tutorial regarding a Java pacman game.

Here is the code in question.

   if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) {
        pos = // integer         
        ch = screendata[pos];

        if ((ch & 16) != 0) { // do not understand this.
            screendata[pos] = (short)(ch & 15);
            ...
        }

I am not really understanding the single &. I understand this operand checks both sides of an if statement, or is a bitwise operator. However, per the tests below, it doesn't seem to be either:

if I was to test (ch = 18):
(ch & 16) = 16
(ch & 8) = 0
(ch & 2) = 2

thanks

& is the bitwise operator AND:

18 = 10010
16 = 10000
----------
16 = 10000


18 = 10010
 8 = 01000
----------
 0 = 00000

So the if will check if the fifth bit is 1 or 0.

The single & it's a bitwise AND . It's an and operation performed on individual bit of your number.

Consider a possible bit representation of your short:

10011011 &   : screendata[pos]
00010000 =   : 16
----------
10010000

Specifically this line:

if ((ch & 16) != 0) {

check if the 5-th bit (2^ (5 -1)) of your number is set to 1 (different from 0).

That's not a Boolean and, which is always && ; instead it's a bitwise and. It's checking to see if the 5th bit from the right is set in ch .

ch = 18  //      ch = 0b00010100
ch & 16  //      16 = 0b00010000
         // ch & 16 = 0b00010000 != 0
ch & 8   //       8 = 0b00001000
         // ch &  8 = 0b00000000 == 0
ch & 2   //       2 = 0b00000010
         // ch &  2 = 0b00000010 != 0

Given ch = 18

(ch & 16) = 16
(ch & 8) = 0
(ch & 2) = 2

seems correct. What's 18 in binary ? 16 | 2 16 | 2 or 10010 in binary.

To be clear, & is a bitwise operator. However && returns true if both operands are true.

Single ampersand is a bitwise AND operator.

You might find it easier to "get" if the values were in hex.

The bitwise and operator & performs an "and" on each bit of the two integers to determine the result.

So:

18 = 0001 0010
16 = 0001 0000
18&16 = 0001 0000

& is bitwise operator AND. You can see detail in http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM