What does the ^ operator do in Java?

前端 未结 17 1747
执念已碎
执念已碎 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:46

    It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1. So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.

提交回复
热议问题