How to swap all odd and even bits in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>

unsigned int swapsOddAndEvenBits(unsigned int n) { 
    unsigned int oddBits  = n & 0xAAAAAAAA; // (binary: 101010...) to isolate odd bits.
    unsigned int evenBits = n & 0x55555555; // (binary: 010101...) to isolate even bits.
    
    std::cout << "oddBits:  " << std::bitset<8>(oddBits) << std::endl;
    std::cout << "evenBits: " << std::bitset<8>(evenBits) << std::endl;

    oddBits >>= 1;  // Right-shift odd bits by 1 to move them to even positions.
    evenBits <<= 1; // Left-shift even bits by 1 to move them to odd positions.
    
    std::cout << "oddBits Right-shift: " << std::bitset<8>(oddBits) << std::endl;
    std::cout << "evenBits Left-shift: " << std::bitset<8>(evenBits) << std::endl;
    
    return (oddBits | evenBits); // Combine shifted bits
}

int main() 
{ 
    unsigned int n = 90; 
    
    std::cout << std::bitset<8>(n) << std::endl;
  
    std::cout << std::bitset<8>(swapsOddAndEvenBits(n)) << std::endl; 
}



/*
run:

01011010
oddBits:  00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
10100101

*/


 



answered Oct 25, 2025 by avibootz
...