basics · intermediate · ~15 min

Reverse 32 bits

Reverse the bit order of a 32-bit word.

Challenge

Implement:

uint32_t reverse_bits(uint32_t x);

Return x with its 32 bits reversed (bit 0 <-> 31, 1 <-> 30, ...).

Input format

A 32-bit value.

Output format

The bit-reversed value.

Constraints

None.

Starter code

#include <stdint.h>
/* Reverse the 32 bits of x (bit 0<->31, 1<->30, ...). */
uint32_t reverse_bits(uint32_t x){ return x; }

Common mistakes

Shifting a uint8_t/int accumulator that can't hold 32 bits.

Edge cases to handle

Reversing twice yields the original (an involution).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.