What does the ^ operator do in Java?

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

    XOR operator rule =>

    0 ^ 0 = 0
    1 ^ 1 = 0
    0 ^ 1 = 1
    1 ^ 0 = 1
    

    Binary representation of 4, 5 and 6 :

    4 = 1 0 0 
    5 = 1 0 1
    6 = 1 1 0
    

    now, perform XOR operation on 5 and 4:

         5 ^ 4 => 1  0  1   (5)
                  1  0  0   (4)
                ----------
                  0  0  1   => 1
    

    Similarly,

    5 ^ 5 => 1   0   1    (5)
             1   0   1    (5)
           ------------
             0   0   0   => (0)
    
    
    5 ^ 6 => 1   0   1  (5)
             1   1   0  (6)
            -----------
             0   1   1  => 3
    

提交回复
热议问题