How to swap two numbers using XOR

Programming

About XOR

  • XOR is also known as eXclusive OR.
  • In programming we denote XOR operator by caret ^
  • XOR operator works with bit i.e., 0 and 1.

XOR Truth Table

XYX ^ Y
000
011
101
110

Note!
If there are odd numbers of 1s then the result is 1.

Now the swap operation


Let the two given numbers be x and y

Example
Let x = 2 and y = 3
In binary:
x = 0010
y = 0011

Steps


Step 1    x = x ^ y
Step 2    y = x ^ y
Step 3    x = x ^ y

Lets do the swap.

Step 1: x = x ^ y


    x = 0010
    y = 0011
---------------
x ^ y = 0001

So in step 1,
x = x ^ y
  = 0001    [in binary]
  = 1       [in decimal]

Step 2: y = x ^ y


    x = 0001    [from step 1]
    y = 0011
---------------
x ^ y = 0010

So in step 2,
y = x ^ y
  = 0010    [in binary]
  = 2       [in decimal]

Step 3: x = x ^ y


    x = 0001    [from step 1]
    y = 0010    [from step 2]
---------------
x ^ y = 0011

So in step 3,
y = x ^ y
  = 0011    [in binary]
  = 3       [in decimal]

Code in C


#include <stdio.h>

int main(){
	int x, y;

	//input
	printf("Enter x: ");
	scanf("%d", &x);
	printf("Enter y: ");
	scanf("%d", &y);

	//swap
	x = x ^ y;
	y = x ^ y;
	x = x ^ y;

	printf("After swap:\nx = %d\ny = %d\n", x, y);
	return 0;
}

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT