Tuesday, April 10, 2007

Swapping of Integer values using XOR(c#)

With reference to,this post the title seem to be one of the frequently asked Interview questions.

Initially I was bit puzzled on how XOR works with swapping Integer values. Did a bit of recollection in "Digital Systems" and got the clue.

To know how the result is determined using XOR logic refer here

Let me go with the same example in the post referred.

int intNumOne = 9,
int intNumTwo = 1;

//Swapping of numbers starts here

intNumOne ^= intNumTwo;
intNumTwo ^= intNumOne;
intNumOne ^= intNumTwo;
Response.Write("Value of First Variable :: " + intNumOne.ToString() + "");
Response.Write("Value of Second Variable :: " + intNumTwo.ToString() + "");

Convert the number as binary and apply XOR rule.

intNumOne ^= intNumTwo:
intNumOne = 9 = 1001
intNumTwo =1 = 0001
-------
intNumOne = 1000 (Applying the XOR rule)
-------
Decimal equivalent of 1000 is 8.

intNumTwo ^= intNumOne:

intNumTwo = intNumTwo ^ intNumOne = 1^8 = 9

intNumOne = intNumOne^ intNumTwo =8 ^9 = 1

Swapping Result:
intNumOne = 1
intNumTwo =9

1 comment:

Vadivel said...

Welcome back to the world of blogging :) Nice to see you start blogging again. Keep 'em coming at regular intervals.