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
For presenting negative numbers in binary we use "Two's complement"
This is how you get negative binary numbers in java, check this link: How are integers internally represented at a bit level in Java?
Then you get: -5 in binary is 11111011 -4 in binary is 11111100 -------- 00000111 = which is 7. That is why output is 7, hope it helps.