networking · beginner · ~10 min

Byte-swap a 32-bit integer

Manual byte assembly with shifts and masks.

Challenge

Implement unsigned bswap32(unsigned x) that reverses the byte order of a 32-bit unsigned integer.

Examples

bswap32(0x12345678) -> 0x78563412
bswap32(0x000000FF) -> 0xFF000000
bswap32(0xDEADBEEF) -> 0xEFBEADDE
bswap32(0)          -> 0

Constraints

  • Pure bit math; no htonl / ntohl.
  • Must work for any 32-bit input including the sign-bit-set case.

Why this matters

Network byte order is big-endian; most CPUs you'll use are little-endian. Converting between them is one of the most common operations in network and file-format code. Knowing how to do it without htonl (which isn't always available, e.g. on bare-metal) is a useful baseline.

Input format

One unsigned.

Output format

Byte-reversed value.

Constraints

Single expression preferred.

Starter code

unsigned bswap32(unsigned x) { /* TODO */ return 0; }

Common mistakes

Forgetting to mask before shifting up (the high bytes leak). Using signed int so shifting wraps incorrectly.

Edge cases to handle

0; 0xFFFFFFFF; values with the high bit set.

Complexity

O(1).

Background lessons

Up next

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