Click here to Skip to main content
15,921,694 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
C#
#include <iostream>

using namespace std;
int main()
{
int a,b;
cout<<"Enter two number"<<endl;
cin>>a>>b;
cout<<"Original value "<<a<<"\t"<<b<<endl;
a=a^b;
b=a^b;
a=a^b;
cout<<"After swaping  "<<a<<"\t"<<b;
}



Here we have use ^ (bitwise operator) but I can't understand the exact process of swapping.
Anybody can tell me how this process work?
Posted

^ is an XOR - the result of each bit XORed with another bits is one if and only if the bits are different.

Expand it all out into the generations and it's pretty obvious:
a1 = a0 xor b0
b1 = a1 xor b0
a2 = a1 xor b1


Substituting for a1, then b1:
a1 = a0 xor b0
b1 = (a0 xor b0) xor b0
a2 = (a0 xor b0) xor ((a0 xor b0) xor b0)


Because XOR is fully associative and commutative we can move the brackets round
b1 = a0 xor (b0 xor b0)
a2 = ((a0 xor a0) xor (b0 xor b0)) xor b0

Since x xor x is always zero for any x,
b1 = a0 xor 0
a2 = (0 xor 0) xor b0
And since x xor 0 is always x for any value of x:
b1 = a0
a2 = b0

And the swap is done.
 
Share this answer
 
Without complex formulas, just remember that xoring twice against a same value gives the starting value back.

b=a^b, aftera=a^b, in fact makes b=a^b^b (that's just a).

Now, a=a^b, being b just a and a just a^b, makes a=a^b^a, that's just b.
 
Share this answer
 
This is relatively simple. The ^operator is the XOR (exclusive OR) operator, that means:
100^101 = 001 e.g. The point is, only if two bits are different, the result is 1.

Now look what comes here:

C++
a=a^b;
b=a^b;


This is the same like:

C++
b = (a^b)^b;


And this is the same like:

C++
b = a^(b^b);


The b^b is always null (no different bits at all), so b = a!

The same is with a in the end:

C++
a = (a^b)^(a^b)^b;
a = (a ^ a) ^ (b ^b ) ^b;
a = b;
 
Share this answer
 
v2
For instance;
C++
a = 1010; //Binary. 
b = 0011; // Binary too. 

a= a^b; // a = 1001
b= a^b; // b = 1010
a= a^b; // a = 0011 


Hope this helps,
Pablo.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900