summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-11-29 22:10:34 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-11-29 22:10:34 +0800
commite18135c4f76c84063ba17b5a0eb03511c2e575e4 (patch)
tree87525dae5dc8fc486b255ccfc6fcfbe00adbb789
parentad74a56171901d906cece1462fa573f17423556f (diff)
downloadk&r-exercises-e18135c4f76c84063ba17b5a0eb03511c2e575e4.tar.gz
2.6
-rw-r--r--2/6.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/2/6.c b/2/6.c
new file mode 100644
index 0000000..67d7c09
--- /dev/null
+++ b/2/6.c
@@ -0,0 +1,35 @@
+#include <stdio.h>
+
+unsigned setbits(unsigned x, int p, int n, unsigned y);
+
+int main(int argc, char *argv[]) {
+ int p, n;
+ unsigned x, y;
+
+ p = 5;
+ n = 3;
+ x = 0;
+ y = 7;
+
+ printf("New bit field: %x\n", setbits(x, p, n, y));
+
+ return 0;
+}
+
+unsigned setbits(unsigned x, int p, int n, unsigned y) {
+ unsigned yLO, yLOA, xUnset, xPrime;
+
+ // extract LO n bits from y
+ yLO = y & ~(~0 << n);
+
+ // align extracted LO bits of y to position p:
+ yLOA = yLO << (p + 1 - n);
+
+ // create mask with n bits from position p unset:
+ xUnset = (~0 << p) | ~(~0 << (p - n));
+
+ // mask out n bits from x starting at position p:
+ xPrime = x & xUnset;
+
+ return xPrime | yLOA;
+} \ No newline at end of file