C++ program to swap bits in a number

Today we will learn how to swap bits in C++ language.

Given an integer n and two-bit positions a1 and a2 inside it, swap bits at the given positions. The given positions are from the least significant bit.

Example-

Input: n = 20

a1 = 2, a2 = 3

n = 10111

after swapping = 11000 = 24

o/p – 24

This is a classic problem of bit manipulation, in which we have to make use of the XOR gate logic, the XOR of two number x & y gives a number which has all bits 1 where bits of x & y differ.

This problem uses the concept of left shift (>>) and XOR (^) bit manipulations.

The left shift operator shifts the bits in the shift expression to the left by the specified number of positions in the additive expression.

Now if we follow 3 steps

  1.  x=x^y
  2.  y=x^y &
  3.  x=x^y

we will obtain the swapping of x and y bits. We will use the same logic to solve this question.

Below is our given C++ program that will able to swap bits in a number:

#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    cout<<"Enter int \n";
    unsigned int n;
    cin>>n;
    unsigned int a1,a2;
    cout<<"enter value to a1 and a2\n";
    cin>>a1>>a2;
    unsigned int bone =  (n >> a1) & 1;
    unsigned int btwo =  (n >> a2) & 1;
    // XOR the two bits
    unsigned int x = (bone ^ btwo);
    //Put the XOR bit back to their original positions
    x = (x << a1) | (x << a2);
    //XOR x with the original number then we will get the final swapper number 
    unsigned int result = n ^ x;
    cout<<"The answer - "<<result<<endl;
    return 0;
}

If we run the above code, we will get the output as you can see below:

Enter integer number
20
enter value to a1 and a2
3 2
The answer is 24

Also read: C++ program to set bits in all numbers from 1 to n

Leave a Reply