summaryrefslogtreecommitdiff
path: root/ch2/2-6.c
diff options
context:
space:
mode:
Diffstat (limited to 'ch2/2-6.c')
-rw-r--r--ch2/2-6.c15
1 files changed, 15 insertions, 0 deletions
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<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));
+}