basics · intermediate · ~15 min

Extract a bit field

Pull a contiguous run of bits out of a word.

Challenge

Implement:

unsigned extract_bits(unsigned x, int pos, int width);

Return the width bits of x starting at bit position pos. pos in 0..31, 1 <= width <= 32-pos.

Input format

x, a start position pos, and a width.

Output format

The extracted field, right-aligned.

Constraints

width may be up to 32 (when pos==0).

Starter code

#include <stddef.h>
/* Extract the width bits of x starting at bit position pos. pos in 0..31, 1<=width<=32-pos. */
unsigned extract_bits(unsigned x,int pos,int width){ (void)x;(void)pos;(void)width; return 0; }

Common mistakes

(1u << width) - 1 is undefined when width==32 — special-case it.

Edge cases to handle

width==32 needs a full mask (avoid 1<<32).

Background lessons

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