Math Fundamentals18 sections · 814 units
Open in Course

Reversing Bits

Mirror the bits

To reverse the bits of a 32-bit integer, you need to swap bit positions: bit 0 becomes bit 31, bit 1 becomes bit 30, and so on.

The approach: initialize a result to 0. For each of the 32 bits in the input, check if the bit is set. If it is, set the corresponding reversed position in the result.

For bit ii in the input, the reversed position is 31i31 - i. Extract bit ii from input, then set bit 31i31 - i in result. After 32 iterations, you have the reversed number.