basics · intermediate · ~15 min

Insert a bit field

Replace a contiguous run of bits in a word.

Challenge

Implement:

unsigned insert_bits(unsigned x, int pos, int width, unsigned val);

Return x with the width bits at pos replaced by the low width bits of val.

Input format

x, pos, width, and a val.

Output format

x with the field overwritten.

Constraints

width up to 32 (pos==0).

Starter code

#include <stddef.h>
/* Replace the width bits of x at position pos with the low width bits of val. pos in 0..31, 1<=width<=32-pos. */
unsigned insert_bits(unsigned x,int pos,int width,unsigned val){ (void)pos;(void)width;(void)val; return x; }

Common mistakes

Not masking val to width (spills into neighbouring fields); the 1<<32 trap again.

Edge cases to handle

val is masked to width; bits outside the field are preserved.

Background lessons

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