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,845 questions

51,766 answers

573 users

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

Related questions

1 answer 65 views
1 answer 65 views
1 answer 54 views
1 answer 43 views
...