What is the bitset::count() function in C++?

The bitset::count() function in C++ is used to count the number of bits that are setbit having a value of 1. This function is available in the bitset header file.

Syntax

The syntax of bitset::count() function is shown below.

int count()

Parameters

The function does not accept any parameters.

Return value

The function returns the number of bits that are setbit having a value of 1 in the binary representation of the integer.

Code

Let’s have a look at the code below.

#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<8> b1 = 10;
bitset<8> b2 = 123;
int b1_set_bits = b1.count();
cout << "Number of Set Bits in " << b1 << ": " << b1_set_bits;
cout << endl;
int b2_set_bits = b2.count();
cout << "Number of Set Bits in " << b2 << ": " << b2_set_bits;
return 0;
}

Explanation

  • In lines 1 and 2, we import the required header files.

  • In lines 6 and 7, we create two bitset objects each having the capacity to store 8 bits. These objects will contain the binary representation of the integers.

  • In line 9, we call the count() function to get the number of setbit having a value of 1 bits.

  • In line 10, we print the binary number with its number of set bits.

  • In lines 13 and 14, we repeat the same process.

In this way, we can calculate the number of setbit having a value of 1 bits in any integer.

Free Resources