GeeksfoGeeks: Swap all odd and even bits
Problem Statement: Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). Here, every even position bit is swapped with an adjacent bit on the right side(even position bits are highlighted in the binary representation of 23), and every odd position bit is swapped with an adjacent on the left side.
Example: 1010 should become - 0101
Solution: We can have our ans number initialized with 0, and we can run a loop for all the bits of the given number. At every iteration get the even odd pair, and add that to the appropriate place in the ans (by left shifting the even and odd bit that you got to the place it needs to be inserted in the answer ans) Below is the working code in java.
//Function to swap odd and even bits.
public static int swapBits(int n)
{
// Your code
int ans = 0;
for(int i=0; i<32; i+=2) {
// Getting the odd and even bits at that point for n
int odd = n & 1;
int even = (n>>1) & 1;
// setting bits in ans at that position, i and i+1
ans = ans | (even<<i);
ans = ans | (odd << i+1);
// right shifting n to get the next set of even and odd bits
n = n>>2;
}
return ans;
}