The Beauty Of The Bitwise XOR

February 20, 2013 5:27 am

It all started with a simple but quite popular problem in C Programming: How would you swap the values of two variables without using a temporary variable?

int a=10, b=5;
a = a+b; // now a=15, b=5
b = a-b; //now a=15, b=10
a = a-b; //now a=5, b=10 mission accomplished

the code above, swaps the values in a and b. But then we came across this:

a^=b;
b^=a;
a^=b;

When we first saw that this actually swaps the values in the two variables, we were stunned. It is just the beauty of the bitwise XOR operator. We spent some time thinking about why and how it works – but the undeniable fact remains that it is a beautiful way to get this simple problem solved.

(We do hope the government does not realize that there is an easier way to swap two variables or they would print two trillion dollar coins)

Have you come across any other such cool tricks? What other beauties do you know of?

For Interesting Statistics Everyday, Find Statspotting on Facebook and Follow Statspotting on Twitter

Leave a Reply