^(插入符号)运算符在Java中起什么作用?

当我尝试这样做时:

int a = 5^n;

...它给我:

当n = 5时,返回0 当n = 4时,返回1 当n = 6时,返回3

...所以我猜它不会取幂。但那是什么呢?


当前回答

异或运算符规则

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

位运算符对位进行操作,并执行逐位操作。假设a = 60, b = 13;现在,在二进制格式中,它们将如下所示

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

其他回答

要执行幂运算,可以使用Math。战俘相反:

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#pow%28double,%20double%29

异或运算符规则=>

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

4、5和6的二进制表示:

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

现在,对5和4执行异或操作:

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

同样的,

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

^ = (按位异或)

描述

如果二进制异或操作符在一个操作数中设置,则复制位。

例子

(A ^ B)会给出49,即0011 0001

正如很多人已经指出的,它是异或运算符。许多人也已经指出,如果您想要求幂,那么您需要使用Math.pow。

但我认为注意到^只是被统称为位操作符的操作符家族中的一个也是有用的:

Operator    Name         Example     Result  Description
a & b       and          3 & 5       1       1 if both bits are 1.
a | b       or           3 | 5       7       1 if either bit is 1.
a ^ b       xor          3 ^ 5       6       1 if both bits are different.
~a          not          ~3          -4      Inverts the bits.
n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

从这里。

当您需要读写整数时,这些操作符可以派上用场,其中各个位应该被解释为标志,或者当整数中的特定位范围具有特殊含义而您只想提取这些位时。您可以在不需要使用这些操作符的情况下进行大量日常编程,但如果您必须在位级上处理数据,那么对这些操作符的良好了解是非常宝贵的。

^是二进制(以2为底)异或,而不是取幂(不能作为Java运算符)。关于取幂,请参见java.lang.Math.pow()。