Mirror a 32-bit Register

Easy · Bits & Math · about 15 min

A hardware register holds a 32-bit unsigned value x. A bug in the wiring reversed the order of its bits: bit 0 became bit 31, bit 1 became bit 30, and so on.

Return the value you get by reversing all 32 bits of x (leading zeros included), as an unsigned number from 0 to 4294967295.

  • 0 <= x <= 4294967295.

Examples:

mirror_register(1) → 2147483648 (bit 0 moves to bit 31)

mirror_register(6) → 1610612736 (bits 1 and 2 move to bits 30 and 29)

Hints

  • Repeat exactly 32 times: take the lowest bit of x, push it onto the answer, then drop it from x.
  • Pushing a bit onto the answer means shifting the answer left by one and OR-ing the bit in.
  • In JavaScript, bit operators give signed 32-bit results: convert back to unsigned at the end.

Learn the pattern first: the Bits & Math lesson.

More Bits & Math problems