# Swapping two numbers using bitwise operator in C++

Hello everyone, this tutorial is about swapping two numbers using the bitwise operator in C++. We will see how we can use bitwise XOR operator to swap two numbers. In this method, we won’t have to use any temporary variable.

## Swap two numbers using bitwise operator in C++

Let us first understand what swapping means. By swapping we exchange the values at two different locations in memory. There are many ways to swap numbers in C++. See this: How to swap two numbers without using third variable in C++

We are going to use a bitwise XOR operator in C++ to swap two numbers in this tutorial. Let us first have a quick look at the working of this method with an example.

Suppose we have a number 23 stored in variable x. Its binary form will be 0001 0111. Let’s say the other number is 34 stored in variable y. Its binary form will be 0010 0010.

**Step 1:** Do bitwise XOR operation for x and y and store the result in x.

x= 0001 0111

y= 0010 0010

x^y= 0011 0101

Now x= 0011 0101 and y= 0010 0010

**Step 2: **Do bitwise XOR operation for y and new value at x and store the result in y.

x= 0011 0101

y= 0010 0010

x^y= 0001 0111

Now x= 0011 0101 and y =0001 0111

**Step 3: **Do bitwise XOR opeartion again for x and y and store the result in x.

x= 0011 0101

y= 0001 0111

x^y= 0010 0010

Now x= 0010 0010 and y 0001 0111

i.e x= 34 and y= 23. The values are swapped now.

Now let’s implement the above in our C++ program.

#include <iostream> using namespace std; int main() { int x = 23, y = 34; cout << "Before swapping x = " << x << " and y = " << y << ".\n"; //swapping using bitwise operator x = x^y; y = x^y; x = x^y; cout << "After swapping x = " << x << " and y = " << y << ".\n"; return 0; }

Output:

Before swapping x = 23 and y = 34. After swapping x = 34 and y = 23.

Hope you understood the concept.

## Leave a Reply