What does the ^ operator do in Java?

2018-12-31 08:21发布

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

When I try this:

int a = 5^n;

...it gives me:

for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3

...so I guess it doesn't perform exponentiation. But what is it then?

17条回答
孤独总比滥情好
2楼-- · 2018-12-31 08:49

AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.

The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.

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.

With 4 and 5, the only difference is in the last place; so

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

查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 08:49

^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().

查看更多
公子世无双
4楼-- · 2018-12-31 08:51

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
查看更多
公子世无双
6楼-- · 2018-12-31 08:51

It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).

查看更多
笑指拈花
7楼-- · 2018-12-31 08:52

As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

查看更多
登录 后发表回答