What does the ^ operator do in Java?

前端 未结 17 1759
执念已碎
执念已碎 2020-11-22 03:27

What function does the ^ (caret) operator serve in Java?

When I try this:

int a = 5^n;

...it gives me:

17条回答
  •  悲哀的现实
    2020-11-22 03:43

    It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

    ex :-

    To use your example:

    The binary representation of 5 is 0101. The binary representation of 4 is 0100.

    A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

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

提交回复
热议问题