basics · intermediate · ~15 min
Pull a contiguous run of bits out of a word.
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.
x, a start position pos, and a width.
The extracted field, right-aligned.
width may be up to 32 (when pos==0).
#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; }
(1u << width) - 1 is undefined when width==32 — special-case it.
width==32 needs a full mask (avoid 1<<32).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.