From c838e15b7f7124e82ba59ae92029957622fdc475 Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Sat, 13 Jul 2019 11:57:09 -0400 Subject: Added 2-6 --- ch2/2-6.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 ch2/2-6.c (limited to 'ch2') diff --git a/ch2/2-6.c b/ch2/2-6.c new file mode 100644 index 0000000..ee6770d --- /dev/null +++ b/ch2/2-6.c @@ -0,0 +1,15 @@ +#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)); +} -- cgit v1.2.3