Computer
Systems

Spring 2013
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 * * 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); } 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/ spring2013/systems/ code/ xor_swap_trick
last modified Wednesday January 30 2013 10:07 pm EST