networking · beginner · ~10 min
Manual byte assembly with shifts and masks.
Reverse the byte order of a 32-bit integer by hand — the swap between big-endian (network) and little-endian (most CPUs), without htonl.
Implement unsigned bswap32(unsigned x) that returns x with its four bytes in reverse order.
x: any 32-bit unsigned value.The byte-reversed value: byte 0 <-> byte 3, byte 1 <-> byte 2.
bswap32(0x12345678) -> 0x78563412
bswap32(0x000000FF) -> 0xFF000000
bswap32(0xDEADBEEF) -> 0xEFBEADDE
bswap32(0) -> 0
0 and 0xFFFFFFFF map to themselves.unsigned, not signed int, for the shifts.htonl / ntohl.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.
x: a single 32-bit unsigned value.
x with its four bytes reversed.
Pure bit math, no htonl/ntohl; use unsigned shifts so the high bit is handled correctly.
unsigned bswap32(unsigned x) { /* TODO */ return 0; }
Forgetting to mask before shifting up (the high bytes leak). Using signed int so shifting wraps incorrectly.
0; 0xFFFFFFFF; values with the high bit set.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.