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

当我尝试这样做时:

int a = 5^n;

...它给我:

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

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


当前回答

正如很多人已经指出的,它是异或运算符。许多人也已经指出,如果您想要求幂,那么您需要使用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.

从这里。

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

其他回答

正如其他人所说,这是按位异或。如果你想求一个数字的给定幂,请使用Math。Pow (a, b)这里a是数字,b是幂。

这是因为使用了异或运算符。

在java或其他语言中,^是位xor, 当然,

10 ^ 1 = 11。 关于逐位操作符的更多信息

有趣的是,Java和c#没有强大的操作符。

它是按位异或,Java没有求幂运算符,你必须使用Math.pow()来代替。

很多人已经解释了它是什么以及如何使用它,但除了显而易见的,你可以使用这个运算符来做很多编程技巧,比如

对布尔数组中的所有元素进行XORing会告诉你数组中是否有奇数个真元素 如果你有一个数组,所有数字都重复偶数次,只有一个数字重复奇数次,你可以通过XORing所有元素找到它。 不使用临时变量交换值 寻找在1到n范围内缺失的数字 对通过网络发送的数据进行基本验证。

很多这样的技巧可以使用比特明智的操作符,有趣的话题来探索。

在Python等其他语言中,您可以执行10**2=100,尝试一下。