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:
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.
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;}
bitset
object that has the capacity to store 4 bits. This object will contain the binary representation of the integer 10.set()
function and print the binary representation that contains all the bits to be set to 1.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++.