basics · beginner · ~15 min
Combine right-shift and mask to extract a byte regardless of host endianness.
Pull a single byte out of a 32-bit word by its position, where byte 0 is the least-significant byte.
Implement unsigned extract_byte(unsigned x, int byte_index) that returns the byte at position byte_index of x:
For any byte_index outside 0..3, return 0.
An unsigned 32-bit word x and an int byte_index.
Returns the selected byte (a value in 0..255) zero-extended into an unsigned. The upper 24 bits of the result must be 0.
extract_byte(0x11223344, 0) -> 0x44
extract_byte(0x11223344, 1) -> 0x33
extract_byte(0x11223344, 3) -> 0x11
extract_byte(0x11223344, 9) -> 0x00 (out of range)
memcpy — use a shift and a mask.Network packet parsers, file-format readers, and binary protocols all extract one byte at a time from a wider integer. Doing it with shifts and masks (rather than memcpy) keeps the logic portable across endianness.
An unsigned 32-bit word x and an int byte_index.
The selected byte (0..255) zero-extended to unsigned; 0 for out-of-range indices.
No loops, no memcpy. Guard out-of-range indices before shifting.
unsigned extract_byte(unsigned x, int byte_index) { /* TODO */ return 0; }
Forgetting & 0xff — the upper bits leak through. Allowing byte_index >= 4 without a guard.
Negative byte_index; byte_index >= 4; the byte being 0xFF.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.