Swapping without 3rd Variable Bitwise

This is a simple  Program for Swapping of 2 Numbers with Bitwise Operators. This is a part of Mumbai University MCA Colleges . It is a Interview Question and Program.




Swapping of 2 numbers with Bitwise operator (without 3rd Variable).


#include <stdio.h>
#include <iostream.h>
int main()
{
int a=11;
int b=20;
b=a^b;
a=a^b;
b=a^b;
printf("%d %d",a,b);
return 0;
}


This Program can also be written as

#include <stdio.h>
#include <iostream.h>
int main()
{
int a=11;
int b=20;
b^=a;
a^=b;
b^=a;
printf("%d %d",a,b);
return 0;
}

The advantage of using bitwise operator program over normal arithmetic program  as follows
b=b+a;
a=b-a;
b=b-a;

is that the above code will lead to overflow i.e if your using a int data (2 Bytes) type then swapping a number 65,535 with other number 65,535 will lead to overflow and will return the garbage value in b=b+a;

The bitwise operators works on the bit level and hence doesnt face the problem of overflow.

We use the bitwise property of XOR gate to generate the desired result.
XOR Gate produces the same number if XORed Twice.

No comments:

Post a comment