XOR, p ^ q
, can be expressed using the and (&
), or (|
), and not/invert (~
) bitwise operators as (p & q) | ~(p & q)
(see Wikipedia’s exclusive or article). Hence, we can now simulate an XOR with the other bitwise operators to do the usual swap.
int x = 1;
int y = 2;
x = (x & y) | ~(x & y);
y = (y & x) | ~(y & x);
x = (x & y) | ~(x & y);
Although note Java will create temporary variables to store the intermediate values in the expression (eg. the results of x & y
), so in practice or on real architectures this is slower than just storing a variable in a temporary, but from a theory perspective it may satisfy your question.
Note that @ytoamn’s answer is a better solution than mine as the JVM wouldn’t need to create extra temporary variables to store intermediate parts of expressions. (And isn’t just an XOR workaround)
5
solved How to swap two variables using bitwise operators (not XOR, and without temporary var) [closed]