networking · beginner · ~10 min
Manual byte assembly with shifts and masks.
Implement unsigned bswap32(unsigned x) that reverses the byte order of a 32-bit unsigned integer.
bswap32(0x12345678) -> 0x78563412
bswap32(0x000000FF) -> 0xFF000000
bswap32(0xDEADBEEF) -> 0xEFBEADDE
bswap32(0) -> 0
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.
One unsigned.
Byte-reversed value.
Single expression preferred.
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.