How does the Java – XOR (^) exchange algorithm work?
This is a way to swap a and B without requiring a third variable I understand whether XOR means "true" or "false" in the real table, but what is it doing here? How does XOR work when the number we are dealing with is not Boolean?
int a = 5; int b = 10; a = a ^ b; b = a ^ b; a = a ^ b;
Solution
For each bit in the binary encoding of each number, the operation is performed once per bit
Have you ever played the game "lights out"? Each light is on or off, and each button is pressed to switch (XOR) a mode If the button is pressed again, the same switch will change the mode The same is true if the combination button is pressed The same button combination will change it – the order does not have to be the same
The same behavior occurs in the game and in the bitwise operation of variables When you put two variables together, the bits in one are used to switch the bits in the other Because of the nature of this change, it doesn't matter which one is switching - the results are the same The same bit at the same position in the two numbers produces 0.5 at that position in the result The opposite bit produces 1.5 at this position
a = a ^ b;
A is now set to the combined bitmask of a and B B is still the original value
b = a ^ b;
B is now set to the combined bitmask of (a XOR b) and B B cancels, so now B is set to the original value of A A is still set to the combined bitmask of a and B
a = a ^ b;
A is now set to the combined bitmask of (a XOR b) and a (remember, B actually contains the original value of a) the cancellation of a, so a is now set to the original value of B