basics · intermediate · ~15 min
Replace a contiguous run of bits in a word.
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.
x, pos, width, and a val.
x with the field overwritten.
width up to 32 (pos==0).
#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; }
Not masking val to width (spills into neighbouring fields); the 1<<32 trap again.
val is masked to width; bits outside the field are preserved.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.