C++ program to swap all odd and even bits
In this tutorial, we try to find a way by which we can swap all the odd and even bits. Say we have a number 76, we swap it at the bit level and convert it into 140. What we do is that we deal with the number at the individual bit level. The bits at the even index are swapped with the adjacent bit on the right side and the odd index bits are swapped with an adjacent on the left side.
How do we do this? Let us define the basic structure and the process we need to follow. We actually right-shift all the even index bits by 1 and turn them into odd bits. In the end, shifting the bits to the left by 1 would turn them even. The final output is in a 32-bit form.
Let us come up with a C++ code for the same.
#include <bits/stdc++.h> using namespace std; unsigned int swap(unsigned int n) { unsigned int even = n & 0xAAAAAAAA; unsigned int odd = n & 0x55555555; even >>= 1; odd <<= 1; return (even | odd); }
We define it as unsigned int to ensure that there is no input of a negative number by the user. We return the result of ‘OR’ of even and odd bits. Now we define the main() and input the number.
int main() { unsigned int n = 76; cout<<"\n the final result is "<<swap(n); return 0; }
We get the output as:
the final result is 140 ....
The full program will be:
#include <bits/stdc++.h> using namespace std; unsigned int swap(unsigned int n) { unsigned int even = n & 0xAAAAAAAA; unsigned int odd = n & 0x55555555; even >>= 1; odd <<= 1; return (even | odd); } int main() { unsigned int n = 76; cout<<"\n the final result is "<<swap(n); return 0; }
Leave a Reply