#include unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) { // set n bits in x starting at p to rightmost n bits of y unsigned offset = (p + 1 - n); unsigned y_mask = y & ~(~0 << n); unsigned bot = x & ~(~0 << offset); unsigned top = (x >> offset << offset) & y_mask; unsigned result = top & bot; return result; } int main() { printf("%x\n", setbits(0xaa, 3, 3, 0x33)); }