A BitSet represents elements with fixed size sequence of N Bits which stores only two values either 0(false) or 1(true). When 0 it means bit is unset when it is 1 means bit is set.

Bitset class emulates space efficient array of boolean values, where each element occupies only one bit. Since it emulates like an array, each bit can be accessed through the indexes where index starts from 0th position. Consider a BitSet Bits, one can access the 3rd bit of the element set through Bits[2].

BitSet has the ability to create BitSet from integers or string through Constructors.Size of the BitSet is fixed at Compile time only. Dynamic Resizing is provided through the vector<bool> class.

Definition:Defined in bitset Header file.

template <size_t N> class bitset; N - Size of the BitSet

Member Types: reference:Proxy class that represents a reference to a bit.

Member Functions: Bit Access Count : Counts set bits. size : Returns Size test : Return Bit Value none : Test if no bit is set all : Test if all bits are set. any : Test if any bit is set. Bit Operations set : Set Bits reset : Reset Bits flip : Flip Bits

Let’s look at some of the examples of the BitSet:

Set all Bits:

Using std::bitset

std::bitset<10> x; x.set(); //Sets all bits to '1'

2. Toggling a bit

Using std::bitset

std::bitset<4> num(std::string("0010")); num.flip(1); // num is now 0000 num.flip(0); // num is now 0001 num.flip(); // num is now 1110 (flips all bits)

3. Checking a bit

Using std::bitset

std::bitset<4> num(std::string("0010")); bool test_bit = num.test(1); // test_bit value is set to true;

4. Setting a bit

Using std::bitset

set(x) or set(x,true) – sets bit at position x to 1.

std::bitset<5> num(std::string("01100")); num.set(0); // num is now 01101 num.set(2); // num is still 01101 num.set(4,true) // num is now 11101

#include<iostream> #include<bitset> using namespace std; int main() { std::bitset<5> num(std::string("01100")); num.set(0); cout<<num << endl; num.set(4,true); cout<<num; return 0; } Output:./a.out 01101 11101

5. Clearing a bit

Using std::bitset

reset(x) or set(x,false) – clears the bit at position x.

std::bitset<5> num(std::string("01100")); num.reset(2); //num is now 01000 num.reset(0); //num is still 01000 num.set(3,false); //num is now 00000

6. Changing the nth bit to x

Using std::bitset

set(n,val) – sets bit n to the value val.

std::bitset<5> num(std::string("00100")); num.set(0,true); // num is now 00101 num.set(2,false); // num is now 00001

References: BitSet Examples in GoalKicker.com

If you have any feedback, Please leave a reply by commenting.