[Geeks for Geeks] Swap all odd and even bits

Swap all odd and even bits

Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). Here, every even position bit is swapped with adjacent bit on the right side(even position bits are highlighted in the binary representation of 23), and every odd position bit is swapped with an adjacent on the left side.

  • Time : O(1)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
public:
//Function to swap odd and even bits.
unsigned int swapBits(unsigned int n)
{
for(long long odd = 0, even = 1; odd < 32; odd+=2, even+=2) {
bool o = n & (1ll<<odd);
bool e = n & (1ll<<even);

if(o) n ^= (1ll<<odd);
if(e) n ^= (1ll<<even);

if(e) n ^= (1ll<<odd);
if(o) n ^= (1ll<<even);
}
return n;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/swap-all-odd-and-even-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.