Swap Odd Even Bits

Bit Manipulation Bitwise Coding

Problem: Swap Odd and Even Bits

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:

  • If the input is 23 (which in binary is 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:

  • Even bits mask: 0x55555555 (binary: 0101...0101)
  • Odd bits mask: 0xAAAAAAAA (binary: 1010...1010)

The algorithm typically follows these steps:

  1. Extract the even bits using the even mask.
  2. Extract the odd bits using the odd mask.
  3. Right shift the odd bits by 1.
  4. Left shift the even bits by 1.
  5. Combine the two results using a bitwise OR operation.

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!