Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43 (00101011). 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.

If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and left shift (<<) all odd bits by 1 so that they become even bits. The following solution is based on this observation. The solution assumes that input number is stored using 32 bits.

Let the input number be x
1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and all odd bits as 0.
2) Get all odd bits of x by doing bitwise and of x with 0x55555555. The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0.
3) Right shift all even bits.
4) Left shift all odd bits.
5) Combine new even and odd bits and return.

[pastacode lang=”c” manual=”%2F%2F%20C%20program%20to%20swap%20even%20and%20odd%20bits%20of%20a%20given%20number%0A%23include%20%3Cstdio.h%3E%0A%20%0Aunsigned%20int%20swapBits(unsigned%20int%20x)%0A%7B%0A%20%20%20%20%2F%2F%20Get%20all%20even%20bits%20of%20x%0A%20%20%20%20unsigned%20int%20even_bits%20%3D%20x%20%26%200xAAAAAAAA%3B%20%0A%20%0A%20%20%20%20%2F%2F%20Get%20all%20odd%20bits%20of%20x%0A%20%20%20%20unsigned%20int%20odd_bits%20%20%3D%20x%20%26%200×55555555%3B%20%0A%20%0A%20%20%20%20even_bits%20%3E%3E%3D%201%3B%20%20%2F%2F%20Right%20shift%20even%20bits%0A%20%20%20%20odd_bits%20%3C%3C%3D%201%3B%20%20%20%2F%2F%20Left%20shift%20odd%20bits%0A%20%0A%20%20%20%20return%20(even_bits%20%7C%20odd_bits)%3B%20%2F%2F%20Combine%20even%20and%20odd%20bits%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20unsigned%20int%20x%20%3D%2023%3B%20%2F%2F%2000010111%0A%20%0A%20%20%20%20%2F%2F%20Output%20is%2043%20(00101011)%0A%20%20%20%20printf(%22%25u%20%22%2C%20swapBits(x))%3B%0A%20%0A%20%20%20%20return%200%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/]

Output:

 43
[ad type=”banner”]