byte b = -0b0101^-0b0100;
System.out.println("Outputs "+b);
//Outputs 7
Why does this output 7 (0b111
) when I was expecting 1 (0b001
)?
Negative numbers are calculated according to "two's complement" arithmetic.
-0b0101 = NOT(0000 0101) + 1 = 1111 1010 + 1 = 1111 1011
-0b0100 = NOT(0000 0100) + 1 = 1111 1011 + 1 = 1111 1100
If you XOR these you get:
0000 0111 = 7