Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bitset
c++
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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;
}
Use bitset::count() function in C++

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.

RELATED TAGS

bitset
c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring