pointers-memory · intermediate · ~15 min

Reverse bits of a uint32

Bitwise shifts and masking.

Challenge

Reverse the order of all 32 bits in an unsigned 32-bit integer: bit 0 becomes bit 31, bit 1 becomes bit 30, and so on.

Task

Implement uint32_t reverse_bits(uint32_t n) that returns n with its 32 bits in fully reversed order. No main — the grader calls it.

Input

A single uint32_t n (0 to 0xFFFFFFFF).

Output

Returns a uint32_t whose bit i equals the input's bit 31 - i.

Example

reverse_bits(1)           ->   0x80000000   (lowest bit moves to the top)
reverse_bits(0x55555555)  ->   0xAAAAAAAA   (every bit shifts one position)
reverse_bits(0xFFFFFFFF)  ->   0xFFFFFFFF

Edge cases

  • n == 0 returns 0.
  • A palindromic pattern (all bits set) is unchanged.

Input format

A single uint32_t n.

Output format

The 32-bit value with its bits in reversed order.

Constraints

Operate on exactly 32 bits.

Starter code

#include <stdint.h>
uint32_t reverse_bits(uint32_t n) { /* TODO */ return 0; }

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