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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if all bits can be made same by flipping two consecutive bits
- Swap bits in a given number
- Swap every two bits in bytes
- How to swap two bits in a given integer?
- Toggle all odd bits of a number
- Set all odd bits of a number
- Change all even bits in a number to 0
- Toggle all even bits of a number
- Set all even bits of a number
- Toggle bits of a number except first and last bits
- Print numbers having first and last bits as the only set bits
- Check if bits of a number has count of consecutive set bits in increasing order
- Two odd occurring elements in an array where all other occur even times
- Number of integers with odd number of set bits
- Count of even set bits between XOR of two arrays
- Check whether bitwise AND of N numbers is Even or Odd
- Count of even and odd set bit with array element after XOR with K
- Query to count odd and even parity elements in subarray after XOR with K
- Count of even and odd set bit Array elements after XOR with K for Q queries
- Check whether a given number is even or odd