void swap (int *a, int *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
return;
}
t = a; a = b; b = t; // t is a third integer variable (swap variable) But here's a way without a swap variable, given as as a macro in C: #define SWAP(a,b) { if (a!=b) { a^=b; b^=a; a^=b; }} // Swap macro by XOR Once you define it, you can say swap(x,y) to swap x and y. The numbers kind of flow through each other and end up swapped.
By using the algorithm of bitwise EORing (Exclusive ORing) the numbers together:If the two numbers are X and Y, then to swap them:X = X EOR YY = Y EOR XX =X EOR Ywill swap them.With knowledge of that algorithm, one then uses the syntax of Javascript to implement it.
A = A xor B B = A xor B A = A xor B in C... A^=B; B^=A; A^=B;
The bitwise XOR operator is ^, or shift 6. The bitwise XOR assignment operator is ^=.
a XOR b is a^b in C language