Trying to understand specific print statement

1

If I had the print statement: System.out.println(x & 0x00000001); Assuming int x = -1;

Why does it print 1?

I understand number systems such as binary, hexadecimal and even some octal. What I don't quite understand is the use of the "&" within the print statement and what it's actually doing.

public static void main(String[] args) 
{
    int x = -1;
    System.out.println(x & 0x00000001);
}

expected results: "I dont quite know"

results: 1

java
binary
asked on Stack Overflow Feb 5, 2019 by (unknown user)

1 Answer

1

The binary representation of -1 is (read about 2's complement to learn more about that):

11111111111111111111111111111111

The binary representation of 0x00000001 is:

00000000000000000000000000000001

when you bit-wise AND the two numbers you get

00000000000000000000000000000001

Hence the output is 1.

answered on Stack Overflow Feb 5, 2019 by Eran

User contributions licensed under CC BY-SA 3.0