Search code examples
javaxorbitmask

What is the difference between "arr[i] ^= 1" and "arr[i] ^1" about XOR?


When I write like below

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

I can get this output.

OUTPUT

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

I think that test[0] = 100 -> test[0]^1 = 101 but it is not.

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

Would you expain what is different?


Solution

  • It's because test[0] value already changed to 101 because of test[0]^=1. test[0]^=1 which is actually test[0] = test[0] ^ 1. So while doing b = test[0] ^ 1 you are actually doing 101 ^ 1 which is 100. So the program output is correct.

    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