Counting Bits in an Integer

During a tech screen I was given the task of writing a function to count the number of bits in an integer given. I thought I’d share what I came up with.

#include <stdio.h>

int count_bits(int i) {
    int bit_count = 0;
    int comparator = 0x1;

    for (int x = 0; x < sizeof(int) * 8; x++) {
        if (comparator & i) {
            bit_count++;
        }

        comparitor <<= 1;
    }

    return bit_count;
}

int main(int argc, char *argv[]) {
    // 1
    printf("%dn", count_bits(1));
    // 2
    printf("%dn", count_bits(3));
    // 4
    printf("%dn", count_bits(0x00011101));
    return 0;
}

I don’t know if there’s a better way to do this, but what I did create a comparator with 1 bit (0x1), loop through the number of bits in an int (sizeof(int)*8), do a bitwise AND to see if that bit is flipped in the int I’m counting against, and then shift left one and do it again.

Collin Donnell @collin