Count Set Bits in C++

Count set bits in C++ three ways: a shift loop, Brian Kernighan's n & (n − 1) trick, and __builtin_popcount, with why negative numbers loop forever.

IntermediateBitwise Operations ProgramsExample 3 of 5
count-set-bits.cpp
1#include <iostream>
2#include <bitset>
3using namespace std;
4
5// Method 1: Using loop
6int countSetBits1(int num) {
7 int count = 0;
8 while (num) {
9 count += num & 1;
10 num >>= 1;
11 }
12 return count;
13}
14
15// Method 2: Using Brian Kernighan's algorithm
16int countSetBits2(int num) {
17 int count = 0;
18 while (num) {
19 num &= (num - 1); // Clears the rightmost set bit
20 count++;
21 }
22 return count;
23}
24
25// Method 3: Using built-in function (GCC)
26int countSetBits3(int num) {
27 return __builtin_popcount(num);
28}
29
30int main() {
31 int numbers[] = {12, 15, 255, 1024, 7};
32
33 cout << "Counting set bits:" << endl;
34 for (int num : numbers) {
35 cout << "\nNumber: " << bitset<16>(num) << " (" << num << ")" << endl;
36 cout << "Method 1: " << countSetBits1(num) << " set bits" << endl;
37 cout << "Method 2: " << countSetBits2(num) << " set bits" << endl;
38 cout << "Method 3: " << countSetBits3(num) << " set bits" << endl;
39 }
40
41 return 0;
42}

Sample Output

Number: 0000010000000000 (1024)

A single 1 bit, so every method reports 1.

Method 2: 8 set bits

255 is 11111111.

In this one

  • How to count bits with & 1 and >>
  • Why n & (n − 1) clears the lowest set bit
  • How __builtin_popcount and std::popcount work
  • Why negative inputs need unsigned

How it works

  1. 1

    For each of 12, 15, 255, 1024, and 7, print 16-bit binary.

  2. 2

    Method 1: add num & 1, shift right, repeat.

  3. 3

    Method 2: num &= num − 1, count, repeat.

  4. 4

    Method 3: __builtin_popcount.

Dry run: Count Set Bits

Kernighan on 12:

  1. 1.1100 & 1011 = 1000 count 1
  2. 2.1000 & 0111 = 0000 count 2
  3. 3.Result 2
Kernighan on 12:
1100 & 1011 = 1000   count 1
1000 & 0111 = 0000   count 2
Result 2

Edge cases

Negative number

Add -1 to the array.

Method 1 never terminates, because right-shifting a negative int keeps filling in 1s. Use unsigned.

Zero

Add 0.

All three give 0; the loops never run.

MSVC

Compile with Visual C++.

__builtin_popcount is not defined. Use std::popcount (C++20) or __popcnt.

What's going on

Counting set bits means counting the 1s in a number's binary form; 12 (1100) has 2. This is also called the population count, or popcount. The program does it three ways and checks they agree.

Method 1 looks at every bit. num & 1 is the lowest bit, 0 or 1, and gets added to the count. num >>= 1 shifts everything right by one, dropping that bit. The loop runs until num is 0, so it takes as many passes as the position of the highest 1: 11 passes for 1024.

Method 2 is Brian Kernighan's trick. num & (num - 1) clears the lowest 1 bit. Subtracting 1 turns the lowest 1 into 0 and the 0s below it into 1s; ANDing with the original wipes all of those. So the loop runs once per 1 bit: just once for 1024 (10000000000), against 11 times for Method 1.

Method 3 is __builtin_popcount, a GCC and Clang built-in that usually compiles to a single CPU instruction. It does not exist in MSVC. In C++20 the portable version is std::popcount from <bit>, which needs an unsigned argument.

bitset<16>(num) prints each number as 16 binary digits so you can count the 1s by hand. 255 is eight 1s, and 7 is three.

Negative numbers break Method 1. A negative int shifted right keeps its sign bit, so num never reaches 0 and the loop runs forever. Passing the value as unsigned int fixes Methods 1 and 2.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <bitset> is there because it provides bitset for binary representation display. Leave one out and the compiler stops at the first name it does not recognize.

Understanding Set Bits

Set Bit Concept:

Set bit: bit with value 1
Clear bit: bit with value 0
Count set bits: number of 1s
Also called "population count" or "Hamming weight"

Applications:

Bit manipulation problems
Cryptography
Error detection
Algorithm optimization

Method 1: Loop Through Bits

Algorithm:

int count = 0;

while (num) {

count += num & 1; // Check rightmost bit

num >>= 1; // Shift right

}

What happens here:

Checks each bit from right to left
Counts bits that are 1
Shifts number right each iteration
Stops when number becomes 0

Time Complexity: O(total bits)

Method 2: Brian Kernighan's Algorithm

Algorithm:

int count = 0;

while (num) {

num &= (num - 1); // Clears rightmost set bit

count++;

}

What happens here:

num & (num - 1) clears rightmost set bit
Each iteration removes one set bit
Counts iterations until num becomes 0
More efficient than method 1

Time Complexity: O(number of set bits)

Why Efficient:

Only iterates for set bits
Skips clear bits
Fewer iterations for sparse numbers

Method 3: Built-in Function

Using __builtin_popcount():

int count = __builtin_popcount(num);

What happens here:

GCC built-in function
Hardware-optimized
Single instruction on many CPUs
Fastest method

Note:

GCC/Clang specific
May not be portable
Use compiler-specific features

When to Use Each Method

Method 1 (Loop):

Simple and clear
Works everywhere
Easy to understand
Good for learning

Method 2 (Brian Kernighan's):

More efficient
O(set bits) instead of O(total bits)
Recommended for production
Good balance of efficiency and portability

Method 3 (Built-in):

Fastest performance
Hardware optimized
GCC/Clang only
Use when performance critical

Important Considerations

Efficiency:

Brian Kernighan's: O(set bits)
Loop method: O(total bits)
Built-in: hardware optimized
Choose based on requirements

Portability:

Loop: portable everywhere
Brian Kernighan's: portable
Built-in: compiler-specific
Consider portability needs

Edge Cases:

Handle negative numbers (signed)
Zero: returns 0
Maximum value: all bits set
Test with various inputs

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

How many passes does Kernighan's loop make for 255?

Pick an answer to check it.

Question 2

What does 20 & 19 equal?

Pick an answer to check it.

Questions people ask

Which method is fastest?

The built-in, then Kernighan's, then the shift loop.

How do I count bits in a long long?

__builtin_popcountll or std::popcount on an unsigned long long.

Where is popcount used?

Hamming distance, bitmask DP, chess engines, and set sizes in bitsets.