2
byte b = -0b0101^-0b0100;
System.out.println("Outputs "+b);
//Outputs 7

Why does this output 7 (0b111) when I was expecting 1 (0b001)?

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Klew
  • 23
  • 3

2 Answers2

3

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
0

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.

Community
  • 1
  • 1
Miljan Rakita
  • 1,433
  • 4
  • 23
  • 44