Tuesday, June 2, 2015

XOR swap


I just learned about the XOR swap and thought it was quite interesting and clever. Even thou its completely useless my nerdiness didn't let me ignore it.
So basically it goes like this.

 y = (y ^ (x = x ^ (y = y^x)));  
and this can be written in a "prettier way" with the ^= operator:

 y ^= x ^= y ^= x;  
this works because for any x and y, x is equal to y^(y^x).





No comments:

Post a Comment