What is the bitset::count() function in C++?
The bitset::count() function in C++ is used to count the number of bits that are 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
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
bitsetobjects each having the capacity to store8bits. These objects will contain the binary representation of the integers. -
In line 9, we call the
count()function to get the number of bits.set bit having a value of 1 -
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