How to swap all odd and even bits in PHP

1 Answer

0 votes
class BitManipulation
{
    /**
     * Prints the 8-bit binary representation of an integer.
     */
    public static function printBinary(int $value): void {
        // Mask with 0xFF to ensure only 8 bits are printed
        $binary = str_pad(decbin($value & 0xFF), 8, '0', STR_PAD_LEFT);
        echo $binary . PHP_EOL;
    }

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

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

        echo "oddBits:  ";
        self::printBinary($oddBits);

        echo "evenBits: ";
        self::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;

        echo "oddBits Right-shift: ";
        self::printBinary($oddBits);

        echo "evenBits Left-shift: ";
        self::printBinary($evenBits);

        // Combine shifted bits
        return $oddBits | $evenBits;
    }
}

$n = 90;

// Original number in binary
BitManipulation::printBinary($n);

$result = BitManipulation::swapOddAndEvenBits($n);

// Final result in binary
BitManipulation::printBinary($result);



/*
run:

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

*/

 



answered Oct 26, 2025 by avibootz
edited Oct 26, 2025 by avibootz
...