summaryrefslogtreecommitdiff
path: root/two/bit.c
diff options
context:
space:
mode:
authorMichael Hunteman <michael@huntm.net>2023-07-04 17:03:53 -0500
committerMichael Hunteman <michael@huntm.net>2023-07-06 17:23:45 -0500
commitbfce8f0d0d828209ec0bec71371ee94a7ad62d3e (patch)
treebdf49ca788ca1ca030d5b1cccfd0c9dffeb3f69f /two/bit.c
Initial commit
Diffstat (limited to 'two/bit.c')
-rw-r--r--two/bit.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/two/bit.c b/two/bit.c
new file mode 100644
index 0000000..28f0e7d
--- /dev/null
+++ b/two/bit.c
@@ -0,0 +1,68 @@
+#include <stdio.h>
+
+void
+itob(int n)
+{
+ for (int i = 15; i >= 0; --i) {
+ int j = n >> i;
+ if (j & 1) {
+ printf("1");
+ } else {
+ printf("0");
+ }
+ }
+ printf("\n");
+}
+
+/*
+ * return x with the n bits that begin at position p inverted, leaving the other
+ * bits unchanged
+ */
+void
+invert(unsigned x, int p, int n)
+{
+ int i;
+ i = 0;
+ while (n > 0) {
+ i |= 1 << p;
+ --p;
+ --n;
+ }
+ x ^= i;
+}
+
+/*
+ * return x with the n bits that begin at position p set to the rightmost n bits
+ * of y, leaving the other bits unchanged
+ */
+void
+setbits(unsigned x, int p, int n, unsigned y)
+{
+ x = x >> (p + 1 - n) & ~(~0 << n);
+ y = y & (~0 << n) | x;
+ printf("%d %d\n", x, y);
+ itob(x);
+ itob(y);
+}
+
+/* count the number of 1-bits */
+int
+bitcount(unsigned x)
+{
+ int b = 0;
+ while (x != 0) {
+ /* deletes rightmost 1-bit in x */
+ x &= (x - 1);
+ ++b;
+ }
+ return b;
+}
+
+int
+main()
+{
+ /* setbits(5, 2, 3, 16); */
+ /* invert(16, 2, 1); */
+ printf("%d\n", bitcount(4));
+ return 0;
+}