0

The similar question was asked under What does the ^ operator do in Java?

But I think something is missing.

According to @Carl Smotricz when we have an example: "A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ."

So:

0101 ^ 0100 = 0001 (5 ^ 4 = 1)

And that is clear but what with:

15^4 based on that logic: 1111 100

should be 0111 but the compiler gives: 1011.

It does not work even if we use: Logic OR:

false || false: false

false || true: true

true || false: true

true || true: true

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Konrad
  • 62
  • 5
  • 9
    `15^4 => 1111^0100 = 1011`. You appear to be equating 4, being 100, as the same thing as 1000. This is not correct, as it would have leading 0s, not trailing 0s. – AntonH Dec 11 '17 at 20:28
  • Don't forget the leading zeros, and OR != XOR. – rgettman Dec 11 '17 at 20:28
  • 1
    Possible duplicate of [What does the ^ operator do in Java?](https://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java) – Gholamali Irani Dec 11 '17 at 21:22

1 Answers1

1

When applying bitwise operators to numbers that take a different amount of bits to represent, you need to add leading zeros so they "align".

In your example of 15 and 4:
15 is indeed 1111. 4 is 100, and you need to add leading zeroes to "pad" it up to four bits, i.e., 0100. Now, xoring between them should give a 1 in any position where the two bits differ - 1011, which is result you observed when trying yourself.

Mureinik
  • 297,002
  • 52
  • 306
  • 350