The bitset::count()
function in C++ is used to count the number of bits that are bitset
header file.
The syntax of bitset::count()
function is shown below.
int count()
The function does not accept any parameters.
The function returns the number of bits that are
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;}
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
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