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

51,765 answers

573 users

How to swap all odd and even bits in Kotlin

1 Answer

0 votes
fun main() {
    val n = 90
    
    println("Input: ${toBitString(n, 8)}")
    
    val result = swapsOddAndEvenBits(n)
    
    println("Result: ${toBitString(result, 8)}")
}

/**
 * Swaps odd and even bits in a 32-bit integer.
 */
fun swapsOddAndEvenBits(n: Int): Int {
    // Mask to isolate odd bits: binary 101010... (hex: 0xAAAAAAAA)
    val oddBits = n and 0xAAAAAAAA.toInt()

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

    println("oddBits: ${toBitString(oddBits, 8)}")
    println("evenBits: ${toBitString(evenBits, 8)}")

    // Shift odd bits right to move them to even positions
    val shiftedOddBits = oddBits ushr 1

    // Shift even bits left to move them to odd positions
    val shiftedEvenBits = evenBits shl 1

    println("oddBits Right-shift: ${toBitString(shiftedOddBits, 8)}")
    println("evenBits Left-shift: ${toBitString(shiftedEvenBits, 8)}")

    // Combine the shifted bits
    return shiftedOddBits or shiftedEvenBits
}

/**
 * Converts an integer to a binary string with fixed width.
 * Pads with leading zeros to match the desired bit width.
 */
fun toBitString(n: Int, width: Int): String {
    val binary = Integer.toBinaryString(n)
    return binary.takeLast(width).padStart(width, '0')
}



/*
run:

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

*/

 



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

Related questions

...