Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


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

Harsh Jain

The bitset::set() function in C++ is used to set the bits either to zero or one depending on how the function is used. Two functionalities can be performed using this function:

  • Set all the bits to one.
  • Set the bit as zero or one at a specified position.

This function is available in the bitset header file.


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

bitset& set();
bitset& set(size_t pos, bool val = true);


The function accepts two optional parameters as shown below:

  • pos: This parameter is an unsigned integer and specifies the bit’s position that needs to be set.

  • val: This parameter is a Boolean value with a default value of true, which specifies 1. This parameter denotes the value that needs to be set; true for 1 and false for 0.

Return value

The function returns a new bitset object that contains the set bits.


Let’s have a look at the code now.

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

int main() {
  bitset<4> b1 = 10;
  cout << "Original value: " << b1 << endl;
  cout << "Flipped all bits: " << b1.set() << endl;
  cout << "Flipped second bit : " << b1.set(2, 0);

  return 0;
Use bitset::set() function in C++


  • In lines 1 and 2, we import the required header files.
  • In line 6, we create one bitset object that has the capacity to store 4 bits. This object will contain the binary representation of the integer 10.
  • In line 7, we print the original bit representation of the integer 10.
  • In line 8, we call the set() function and print the binary representation that contains all the bits to be set to 1.
  • In line 9, we again call the set() function, but this time we pass the argument as 2 to set only the second bit and 0 to set zero at the second bit and then we print the new binary representation.

So, in this way, we can set the bits to zero or one of any number using the set() function in C++.



View all Courses

Keep Exploring