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
numberwith the input integernandreversedwith0.reversedwill 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
reversedLeft:reversed shl 1shifts all bits inreversedto the left by one position. This operation makes room for adding the next bit fromnumber. - Add Rightmost Bit of
numbertoreversed:reversed or (number and 1)adds the rightmost bit ofnumbertoreversed.number and 1isolates the rightmost bit ofnumber(because1in binary is...0001, so theANDoperation will zero out all bits except the least significant one). TheORoperation then adds this bit toreversed. - Shift
numberRight:number shr 1shifts all bits innumberto 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,
reversedcontains the bits ofnumberin 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.