Given an unsigned integer, write a function that swaps all the odd bits with the even bits. In this problem, bit indexing starts at 0 (the least significant bit). For every pair of adjacent bits, the bit at position 0 swaps with the bit at position 1, the bit at position 2 swaps with the bit at position 3, and so on.
For example:
10111
), the function should swap every adjacent pair of bits and return the resulting integer.Hint: Use bit masks to extract odd and even bits. A common approach is:
0x55555555
(binary: 0101...0101
)0xAAAAAAAA
(binary: 1010...1010
)The algorithm typically follows these steps:
This exercise is a great way to practice bit manipulation, a fundamental skill in optimizing low-level operations. Have fun coding and experimenting with bit-level operations!