Computer
Systems

Fall 2010
course
navigation

xor swap trick

/* swap.c * * the xor swap trick * * Usage: * $ ./swap * before swap: x=1234, y=4792 * after swap : x=4792, y=1234 * or * $ ./swap 823 101 * before swap: x=823, y=101 * after swap : x=101, y=823 * or * $ ./swap 1 2 verbose * address of x is 0xbfc0fcdc * address of y is 0xbfc0fcd8 * before swap: x=1, y=2 * after swap: x=2, y=1 * * This is explained on wikipedia's 'XOR swap algorithm' page. */ #include <stdio.h> void swap(int* xp, int* yp){ *xp = *xp ^ *yp; // Effectively it looks like this: *yp = *xp ^ *yp; // y_new = (x ^ y) ^ y *xp = *xp ^ *yp; // x_new = (x ^ y) ^ (x ^ y ^ y) } int main(int argc, char* argv[]){ int x = 1234; int y = 4792; if (argc >= 3){ sscanf(argv[1], "%d", &x); sscanf(argv[2], "%d", &y); } if (argc >= 4){ printf("address of x is %p \n", (void*) &x); printf("address of y is %p \n", (void*) &y); } printf("before swap: x=%i, y=%i \n", x, y); swap(&x, &y); printf("after swap : x=%i, y=%i \n", x, y); return 0; }
http://cs.marlboro.edu/ courses/ fall2010/systems/ code/ xor_swap_trick
last modified Wednesday January 30 2013 10:17 pm EST