Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bitset
c++
size
communitycreator

What is bitset::size() function in C++?

Harsh Jain

The bitset::size() function in C++ is used to get the number of bits available in the bitset object. This function is available in the bitset header file.

Syntax

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

size_t& size();

Parameters

The function does not accept any parameters.

Return value

The function returns the number of bits present in the binary representation of the integer. The returned value is an unsigned integer value.

Code

Let’s have a look at the code.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
  bitset<4> b1 = 10;
  bitset<8> b2 = 110;

  cout << "Size of " << b1 << " : " << b1.size();
  cout << endl;
  cout << "Size of " << b2 << " : " << b2.size();

  return 0;
}
Use bitset::size() 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 having the capacity to store 4 and 8 bits respectively. This object will contain the binary representation of the integer 10 and 110 respectively.

  • In line 9, we call the size() function and print the size of the first bitset object.

  • In line 11, we repeat the same process.

  • In the output, we can see the number of bits present in the two binary representations.

RELATED TAGS

bitset
c++
size
communitycreator
RELATED COURSES

View all Courses

Keep Exploring