关于异或的"arr[i] ^= 1"和"arr[i] ^1"有什么区别?

  • 本文关键字:arr 区别 于异 java xor bitmask
  • 更新时间 :
  • 英文 :


当我在下面写

int [] test = {4};
int a = test[0]^=1;
int b = test[0]^1;

我可以得到这样的输出。

输出
test[0]^=1 : 5 a : 101
test[0]^1 : 4 b : 100

我认为test[0] = 100 ->测试[0]^1 = 101,但它不是。

100 
XOR   1
----------
101

你能解释一下有什么不同吗?

这是因为test[0]的值已经因为test[0]^=1而变成了101test[0]^=1实际上是test[0] = test[0] ^ 1。所以在做b = test[0] ^ 1的同时,你实际上在做101 ^ 1,也就是100。因此程序输出是正确的。

int [] test = {4};   // test[0] = 4 = 100
int a = test[0]^=1;  // test[0] = 100 ^ 1 = 101 = 5, a = 5 = 101
int b = test[0]^1;   // test[0] = 5, b = 101^1 = 100 = 4

最新更新