Let two numbers be
n1= 5 //0000 0101
n2= 8 //0000 1000
Let's perform the aforementioned steps:
1. n1=n1^n2
n1= 0000 0101 ^ 0000 1000 = 0000 1101
2. n2=n1^n2
n2= 0000 1101 ^ 0000 1000= 0000 0101 //5=n1(original value of n1) actually
3. n1= n1^ n2
n1= 0000 1101 ^ 0000 0101 = 0000 1000 //8 =n2 (original value of n2) actually
C implementation to swap two Integers using Bitwise Operators
#include <stdio.h>
int main()
{
int n1,n2;
printf("enter two numbers\n");
scanf("%d %d",&n1,&n2);
printf("before swapping...\n");
printf("first no is %d, second no %d\n",n1,n2);
//swapping using bitwise operators
n1=n1^n2;
n2=n1^n2;
n1=n1^n2;
//n1 & n2 is swapped
printf("after swapping...\n");
printf("first no is %d, second no %d\n",n1,n2);
return 0;
}
Output
enter two numbers
5 7
before swapping...
first no is 5, second no 7
after swapping...
first no is 7, second no 5
Algorithm:
This results in swapping as n1 contains new value of n2 and vice versa.
Reason:
Example with explanation
C implementation to swap two Integers using Bitwise Operators
Output
need an explanation for this answer? contact us directly to get an explanation for this answer