Konrad
Konrad

Reputation: 72

How the ^ operator works in java? Supplemental

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

Upvotes: 0

Views: 68

Answers (1)

Mureinik
Mureinik

Reputation: 311163

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.

Upvotes: 1

Related Questions