How to swap all odd and even bits in Swift

1 Answer

0 votes
import Foundation

/// Swaps odd and even bits in a 32-bit unsigned integer.
func swapsOddAndEvenBits(_ n: UInt32) -> UInt32 {
    // Mask to isolate odd bits: binary 101010... (hex: 0xAAAAAAAA)
    let oddBits = n & 0xAAAAAAAA

    // Mask to isolate even bits: binary 010101... (hex: 0x55555555)
    let evenBits = n & 0x55555555

    print("oddBits: \(toBitString(oddBits, width: 8))")
    print("evenBits: \(toBitString(evenBits, width: 8))")

    // Shift odd bits right to move them to even positions
    let shiftedOddBits = oddBits >> 1

    // Shift even bits left to move them to odd positions
    let shiftedEvenBits = evenBits << 1

    print("oddBits Right-shift: \(toBitString(shiftedOddBits, width: 8))")
    print("evenBits Left-shift: \(toBitString(shiftedEvenBits, width: 8))")

    // Combine the shifted bits
    return shiftedOddBits | shiftedEvenBits
}

/// Converts a number to a binary string with fixed width.
/// Pads with leading zeros to match the desired bit width.
func toBitString(_ n: UInt32, width: Int) -> String {
    let binary = String(n, radix: 2)
    return String(repeating: "0", count: max(0, width - binary.count)) + binary.suffix(width)
}

let n: UInt32 = 90

print("Input: \(toBitString(n, width: 8))")

let result = swapsOddAndEvenBits(n)

print("Result: \(toBitString(result, width: 8))")



/*
run:
 
Input: 01011010
oddBits: 00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
Result: 10100101
 
*/

 



answered Oct 26, 2025 by avibootz
...