QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Count Set Bits

Counts the number of set bits in an int

  • bit-manipulation
  • count

Code

int count_set_bits(int n) {
    int count = 0;
    while (n) {
        n &= (n - 1);
        count++;
    }
    return count;
}

Usage

count_set_bits(5);   // Returns: 2
count_set_bits(255); // Returns: 8
count_set_bits(8);   // Returns: 1