basics · intermediate · ~15 min

Byte-swap a 32-bit value

Move bytes between positions with shifts and masks.

Challenge

Reverse the byte order of a 32-bit integer — the core of converting between endiannesses.

Task

Implement uint32_t swap_u32(uint32_t x) that returns x with its four bytes in reverse order, so 0x11223344 becomes 0x44332211. Move each byte to its mirrored position using shifts and masks. No main — the grader calls it.

Input

A single uint32_t x.

Output

Returns x with its byte order reversed, as a uint32_t.

Example

swap_u32(0x11223344)   ->   0x44332211
swap_u32(0x000000FF)   ->   0xFF000000
swap_u32(0)            ->   0

Edge cases

  • 0 swaps to 0.

Rules

  • Use shifts and masks (no <arpa/inet.h> or builtins required).

Input format

A single uint32_t x.

Output format

x with its four bytes reversed, as a uint32_t.

Constraints

Use shifts and masks.

Starter code

#include <stdint.h>

uint32_t swap_u32(uint32_t x) {
    /* TODO */
    return 0;
}

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