How to swap all odd and even bits in C#

1 Answer

0 votes
using System;

class BitManipulation
{
    // Prints the 8-bit binary representation of an integer.
    static void PrintBinary(long value) {
        Console.WriteLine(Convert.ToString(value & 0xFF, 2).PadLeft(8, '0'));
    }

    // Swaps odd and even bits in a 32-bit integer.
    static long SwapOddAndEvenBits(int n) {
        // (binary: 101010...) to isolate odd bits.
        long oddBits = n & 0xAAAAAAAA;

        // (binary: 010101...) to isolate even bits.
        long evenBits = n & 0x55555555;

        Console.Write("oddBits:  ");
        PrintBinary(oddBits);

        Console.Write("evenBits: ");
        PrintBinary(evenBits);

        // Right-shift odd bits by 1 to move them to even positions.
        oddBits >>= 1;

        // Left-shift even bits by 1 to move them to odd positions.
        evenBits <<= 1;

        Console.Write("oddBits Right-shift: ");
        PrintBinary(oddBits);

        Console.Write("evenBits Left-shift: ");
        PrintBinary(evenBits);

        // Combine shifted bits
        return oddBits | evenBits;
    }

    static void Main()
    {
        int n = 90;

        // Original number in binary
        PrintBinary(n);

        long result = SwapOddAndEvenBits(n);

        // Final result in binary
        PrintBinary(result);
    }
}


/*
run:

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

*/

 



answered Oct 25, 2025 by avibootz
...