What does the ^ operator do in Java?

前端 未结 17 1966
执念已碎
执念已碎 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条回答
  •  萌比男神i
    2020-11-22 03:48

    XOR operator rule

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

    Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

    a = 0011 1100
    
    b = 0000 1101
    
    
    
    a^b ==> 0011 1100  (a)
            0000 1101  (b)
            -------------  XOR
            0011 0001  => 49
    
    (a ^ b) will give 49 which is 0011 0001
    

提交回复
热议问题