Swap two numbers using bitwise operator - C Program

Write a C Program to swap two numbers using bitwise operator.

Solution:

Using bitwise X-OR to swap two numbers.

Following is a table of X-OR:

yzy X-OR z
110
101
011
000

Procedure to swap two numbers using bitwise operator.

1) x = x^y
2) y = y^x
3) x = x^y

Let us take an example, x = 12, y = 14

Step-1
x = x^y
x = 1100 Initial value of x
y = 1110 Initial value of y
x^y = 0010
New value of x = 0010

Step-2
y = y^x
x = 0010 New value of x
y = 1110 Old value of y
y^x = 1100
y = 1100

Step-3
x = x^y
x = 0010 New value of x (From step-1)
y = 1100 New value of y(From step-2)
x^y = 1110
x = 1110 New value of x equals to initial value of y.

#include<stdio.h>
int main()
{
     int a, b;
     printf("\tEnter Two Numbers\n");
     printf("----------------------------\n");
     printf("Enter First Number  : ");
     scanf("%d", &a);
     printf("\nEnter Second Number : ");
     scanf("%d",&b);
     printf("\nNumbers Before Exchange");
     printf("\n----------------------------\n");
     printf("a = %d and b = %d\n", a, b);
     /* Swap Variables Using Bitwise Operator */
     a = a ^ b;
     b = a ^ b;
     a = a ^ b;
     printf("\nNumbers After Exchange");
     printf("\n----------------------------\n");
     printf("a = %d and b = %d", a, b);
     return(0);
}


Output:

bitwise operator swapping