Set bit count in a binary number using C

This x=x&(x-1) removes the lowest set bit from the binary string. If you count the number of times you remove the lowest bit before the number becomes 0, you'll get the number of bits that were set.

char numBits(char x){
    char i = 0;
    if(x == 0)
        return 0;
    for(i = 1; x &= x-1; i++);
    return i;
}

doing x = x & (x-1) will remove the lowest bit set. So in your case the iterations will be performed as,

loop #1: 00110101(53) & 00110100(52) = 00110100(52) :: num bits = 1

loop #2: 00110100(52) & 00110011(51) = 00110000(48) :: num bits = 2

loop #3: 00110000(48) & 00101111(47) = 00100000(32) :: num bits = 3

loop #3: 00100000(32) & 00011111(31) = 00000000( 0) :: num bits = 4

The number of iterations allowed will be the total number of bits in the given number.

Tags:

C

Bit