basics · beginner · ~15 min
Combine right-shift and mask to extract a byte regardless of host endianness.
Implement unsigned extract_byte(unsigned x, int byte_index) that returns the byte at the given index from a 32-bit word.
byte_index == 0 returns the least-significant byte (bits 0..7).byte_index == 1 returns bits 8..15.byte_index == 2 returns bits 16..23.byte_index == 3 returns the most-significant byte (bits 24..31).byte_index outside 0..3, return 0.extract_byte(0x11223344, 0) -> 0x44
extract_byte(0x11223344, 1) -> 0x33
extract_byte(0x11223344, 2) -> 0x22
extract_byte(0x11223344, 3) -> 0x11
extract_byte(0x11223344, 9) -> 0x00
0..255), so the upper bits of the return must be 0.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.
x is a 32-bit unsigned word; byte_index is an int.
The selected byte, zero-extended to unsigned.
No loops. No memcpy. Guard out-of-range indices.
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.