networking · beginner · ~10 min

Byte-swap a 32-bit integer

Manual byte assembly with shifts and masks.

Challenge

Reverse the byte order of a 32-bit integer by hand — the swap between big-endian (network) and little-endian (most CPUs), without htonl.

Task

Implement unsigned bswap32(unsigned x) that returns x with its four bytes in reverse order.

Input

  • x: any 32-bit unsigned value.

Output

The byte-reversed value: byte 0 <-> byte 3, byte 1 <-> byte 2.

Example

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

Edge cases

  • 0 and 0xFFFFFFFF map to themselves.
  • Values with the high bit set must work — use unsigned, not signed int, for the shifts.

Rules

  • Pure bit math; do not call htonl / ntohl.

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

x: a single 32-bit unsigned value.

Output format

x with its four bytes reversed.

Constraints

Pure bit math, no htonl/ntohl; use unsigned shifts so the high bit is handled correctly.

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.