Reversing the bits of an integer

Reversing the bits of an integer means to flip the order of the bits in its binary representation. For example, if you have a 32-bit integer, reversing the bits would mean the bit at position 0 (rightmost bit) moves to position 31 (leftmost bit), the bit at position 1 moves to position 30, and so on, effectively mirroring the bit pattern.

Here’s how you can reverse the bits of a 32-bit integer in Kotlin:

Kotlin
fun reverseBits(n: Int): Int {
    var number = n
    var reversed = 0
    for (i in 0 until 32) { // Loop through each bit
        reversed = reversed shl 1  // Shift reversed left to make room for the next bit
        reversed = reversed or (number and 1) // Add the rightmost bit of number to reversed
        number = number shr 1 // Shift number right to process the next bit
    }
    return reversed
}

fun main() {
    val number = 0b00000010100101000001111010011100
    val reversedNumber = reverseBits(number)
    println("Original number (binary): ${Integer.toBinaryString(number)}")
    println("Reversed number (binary): ${Integer.toBinaryString(reversedNumber)}")
}

Explanation:

  • Initial Setup: We initialize number with the input integer n and reversed with 0. reversed will hold the result as we build it bit by bit.
  • Loop Through Each Bit: We loop 32 times because we’re assuming a 32-bit integer. For each iteration, we perform a series of operations to reverse the bits.
  • Shift reversed Left: reversed shl 1 shifts all bits in reversed to the left by one position. This operation makes room for adding the next bit from number.
  • Add Rightmost Bit of number to reversed: reversed or (number and 1) adds the rightmost bit of number to reversed. number and 1 isolates the rightmost bit of number (because 1 in binary is ...0001, so the AND operation will zero out all bits except the least significant one). The OR operation then adds this bit to reversed.
  • Shift number Right: number shr 1 shifts all bits in number to the right by one position. This operation moves the next bit to be processed into the rightmost position for the next iteration.
  • Result: After completing the loop, reversed contains the bits of number in reverse order.

This function effectively reverses the bits of a 32-bit integer, which can be useful in various bit manipulation tasks, such as those found in low-level programming and systems design.

Leave a Comment