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

Pull a single byte out of a 32-bit word by its position, where byte 0 is the least-significant byte.

Task

Implement unsigned extract_byte(unsigned x, int byte_index) that returns the byte at position byte_index of x:

  • index 0 -> bits 0..7 (least-significant byte)
  • index 1 -> bits 8..15
  • index 2 -> bits 16..23
  • index 3 -> bits 24..31 (most-significant byte)

For any byte_index outside 0..3, return 0.

Input

An unsigned 32-bit word x and an int byte_index.

Output

Returns the selected byte (a value in 0..255) zero-extended into an unsigned. The upper 24 bits of the result must be 0.

Example

extract_byte(0x11223344, 0)   ->   0x44
extract_byte(0x11223344, 1)   ->   0x33
extract_byte(0x11223344, 3)   ->   0x11
extract_byte(0x11223344, 9)   ->   0x00   (out of range)

Edge cases

  • Negative or >= 4 indices return 0, not undefined behaviour.
  • A byte value of 0xFF must come back as exactly 0xFF (mask off the higher bytes).

Rules

  • No loops, no memcpy — use a shift and a mask.

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

An unsigned 32-bit word x and an int byte_index.

Output format

The selected byte (0..255) zero-extended to unsigned; 0 for out-of-range indices.

Constraints

No loops, no memcpy. Guard out-of-range indices before shifting.

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.