Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to swap all odd and even bits in C

1 Answer

0 votes
#include <stdio.h>

// Function to print 8-bit binary representation
void printBinary8(unsigned int n) {
    for (int i = 7; i >= 0; i--) {
        printf("%d", (n >> i) & 1);
    }
    printf("\n");
}

// Function to swap odd and even bits
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.

    printf("oddBits:  ");
    printBinary8(oddBits);

    printf("evenBits: ");
    printBinary8(evenBits);

    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.

    printf("oddBits Right-shift: ");
    printBinary8(oddBits);

    printf("evenBits Left-shift: ");
    printBinary8(evenBits);

    return (oddBits | evenBits); // Combine shifted bits
}

int main() {
    unsigned int n = 90;

    printBinary8(n); // Original number in binary

    unsigned int result = swapsOddAndEvenBits(n);

    printBinary8(result); // Final result in binary

    return 0;
}



/*
run:

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

*/

 



answered Oct 25, 2025 by avibootz
...