Math Fundamentals18 sections · 814 units
Open in Course

Reverse Bits - Building the Result

Shift and accumulate

To reverse the bits, process nn from right to left (using n&1n \& 1 to get the current bit, then shifting nn right). Simultaneously build the result from left to right (shifting the result left and adding the new bit).

Initialize result=0result = 0. For each of the 32 bits: shift resultresult left by 1 (making room for the next bit), extract the rightmost bit of nn using n&1n \& 1, add that bit to resultresult using OR (|), then shift nn right by 1.

After 32 iterations, you have processed all bits of nn and built the reversed result. The key is synchronizing two shifts: left for the result, right for the input.