exercise

2026-09-07

//run this example code? bitcount: count 1 bits in x ```c int bitcount(unsigned x) { int b; for (b = 0; x != 0; x >>= 1) if (x & 01) b++; return b; }

```c
#include <stdio.h>
//compile with: gcc -Wall -Wextra cc-c.c -o cc-c

// bitcount:  count 1 bits in x 
int bitcount(unsigned x)
{
    int b;
    for (b = 0; x != 0; x >>= 1)
        if (x & 01)
            b++;
    return b;
}

int main(void)
{
    printf("bitcount(0)    = %d\n", bitcount(0));
    printf("bitcount(1)    = %d\n", bitcount(1));
    printf("bitcount(7)    = %d\n", bitcount(7));
    printf("bitcount(0x6A) = %d   -- 0x6A is 01101010, four 1-bits\n", bitcount(0x6A));
    printf("bitcount(0xFF) = %d\n", bitcount(0xFF));
    printf("bitcount(~0u)  = %d   -- all bits set, so this equals the width of unsigned\n", bitcount(~0u));

    return 0;
}

win@DESKTOP-MEIH88T:~/webdev-projects$ gcc -Wall -Wextra cc-c.c -o cc-c win@DESKTOP-MEIH88T:~/webdev-projects$ ./cc-c bitcount(0) = 0 bitcount(1) = 1 bitcount(7) = 3 bitcount(0x6A) = 4 -- 0x6A is 01101010, four 1-bits bitcount(0xFF) = 8 bitcount(~0u) = 32 -- all bits set, so this equals the width of unsigned