basics · beginner · ~15 min

Extract a byte from a 32-bit word

Combine right-shift and mask to extract a byte regardless of host endianness.

Challenge

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).
  • For byte_index outside 0..3, return 0.

Examples

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

Edge cases

  • Out-of-range indices return 0 (not undefined behaviour).
  • The result fits in a single byte (0..255), so the upper bits of the return must be 0.

Why this matters

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.

Input format

x is a 32-bit unsigned word; byte_index is an int.

Output format

The selected byte, zero-extended to unsigned.

Constraints

No loops. No memcpy. Guard out-of-range indices.

Starter code

unsigned extract_byte(unsigned x, int byte_index) { /* TODO */ return 0; }

Common mistakes

Forgetting & 0xff — the upper bits leak through. Allowing byte_index >= 4 without a guard.

Edge cases to handle

Negative byte_index; byte_index >= 4; the byte being 0xFF.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.