summaryrefslogtreecommitdiff
path: root/ch2/2-6.c
blob: ee6770d47f3a0f7ee5219ef09202f2b8541e5669 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>

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));
}