Here is the program to swap bit in odd and even positions of 32-bit unsigned integer.
For Even- To do this we can AND with bitmask 0xAAAAAAAAAA. The number 0xAAAAAAAA which is a 32 bit number with even bits set (0xA is decimal 10, 1010 binary).
For Odd – For selecting all the odd bits we can AND with bitmask 0×55555555, which is a number with all odd bits sets (0x5 is decimal5, 0101 in binary)
Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side we actually need to shift left (respectively right) of one position and OR the two results.
unsigned int swapBits(unsigned int x)
{
unsigned int evenBits = x & 0xAAAAAAAA;
unsigned int oddBits = x & 0x55555555;
evenBits >>= 1; // Right shift even bits
oddBits <<= 1; // Right shift odd bits
return (evenBits | oddBits); // Combine even and odd bits
}