Swap bits at ith and jth position of integer n

 

#include <iostream> 
using namespace std;

//function to swap bits of an integer n
unsigned swapBit(unsigned int n, unsigned int i, unsigned int j)
{
if(( n & (1 << (i-1))) != (n & (1 << (j-1)))){
n ^= (1 << (i-1)) ^ (1 << (j-1));
}
return n;
}

int main()
{
unsigned int n = 7, i = 1, j = 4 ;
unsigned int result = swapBit(n,i,j);
cout << "After swapping the bit at position "<< i <<" and "<< j << " of integer "<< n << ", we get "<< result<<"." << endl;
return 0;
}

Comments

Popular posts from this blog

Clear right most set bit of an integer n

Toggle the bit at Kth position of integer n