Swap all odd and even bits | C ++ program to swap even and odd bits of a given number ; Function to swap even and odd bits ; Get all even bits of x ; Get all odd bits of x ; Right shift even bits ; Left shift odd bits ; Combine even and odd bits ; Driver code ; 00010111 ; Output is 43 ( 00101011 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int swapBits ( unsigned int x ) { unsigned int even_bits = x & 0xAAAAAAAA ; unsigned int odd_bits = x & 0x55555555 ; even_bits >>= 1 ; odd_bits <<= 1 ; return ( even_bits odd_bits ) ; } int main ( ) { unsigned int x = 23 ; cout << swapBits ( x ) ; return 0 ; }