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 Scala

1 Answer

0 votes
object BitSwapper {

  def main(args: Array[String]): Unit = {
    val n: Int = 90
    
    println(s"Input: ${toBitString(n, 8)}")
    
    val result = swapsOddAndEvenBits(n)
    
    println(s"Result: ${toBitString(result, 8)}")
  }

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

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

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

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

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

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

    // Combine the shifted bits
    shiftedOddBits | shiftedEvenBits
  }

  /**
   * Converts a number to a binary string with fixed width.
   * Pads with leading zeros to match the desired bit width.
   */
  def toBitString(n: Int, width: Int): String = {
    val binary = n.toBinaryString
    if (binary.length >= width) binary.takeRight(width)
    else "0" * (width - binary.length) + binary
  }
}



/*
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

1 answer 59 views
1 answer 67 views
1 answer 46 views
1 answer 53 views
...