Bitset in C++ | Useful for bit manipulation

BITSET in C++

Bitset is a container in C++ STL for dealing with data at bit level.
It can have only two states - 0 or 1 (false or true)

How Bitset is different from boolean array or numeric array or char array

  1. Optimized space allocation (In bitset, each element occupies only one bit)
  2. You can construct bitset from both integer values and binary strings

Constraints
Size of the bitset should be fixed at compile time

Syntax

#include <bitset>
using namespace std;

#define SIZE = 8

bitset<SIZE> bset1;  // 00000000
bitset<SIZE> bset2(7); //00000111
bitset<8> bset3 (string("1010")); //00001010

Indexing in bitset

Index starts at LSB unlike arrays where index starts at MSB.
Index value ranges from 0 to SIZE-1 from right to left

Access element in bitset
Use [ ] operator to access the element at pos.

#include <bitset>
using namespace std;

bitset<4> bset; //0000

bset[1] = 1;
cout<<bset; // 0010

Count number of 1's and 0's in a bitset

#include <bitset>
using namespace std;

bitset<4> bset; //0000

bset[1] = 1;
cout<<"Number of bits set to 1 "<<bset.count(); // 1
cout<<"Number of bits set to 0 "<<bset.size()-bset.count(); // 3
cout<<bset.test(1);
cout<<bset.test(1);

Check if an element in bitset is 1 or 0

test() function is used to check whether a bit at an index is 1 or 0
Returns true if that bit is 1 else 0

#include <bitset>
using namespace std;

bitset<4> bset; //0000

bset[0] = 1;
bset[2] = 1;
cout<<bset; // 0101
cout<<bset.test(1); // false
cout<<bset.test(0);  //true

Check if a bitset contains atleast 1 bit (is set) have 1
any() is used to check if any of the bits in the bitset is set (to one), and false otherwise.

#include <bitset>
using namespace std;

bitset<4> bset; //0000
bitset<4> bset1(7); //0111

cout<<bset.any(); // false
cout<<!bset.any();  //true
cout<<bset1.any(); // true

Check if all bits are 0
none() is opposite to any()
none() returns true if all bits in the bitset are 0 (none of the bits are 1)

#include <bitset>
using namespace std;

bitset<4> bset; //0000
bitset<4> bset1(1); //0001

cout<<bset.none(); // true
cout<<bset1.none(); // false

Check if all bits are 1

all() returns true if all of the bits in the bitset are set (to 1).

#include <bitset>
using namespace std;

bitset<4> bset(15); //1111
bitset<4> bset1(0); //0000

cout<<bset.all(); // true
cout<<bset1.all(); // false

Set all bits to 1 and 0 and toggle between values

#include <bitset>
using namespace std;

bitset<4> bset; //0000

cout<<bset.set(); // 1111
cout<<bset.reset(); // 0000

bitset<4> bset_1(10); //1010

cout<<bset_1.flip(); //0101

Bit access

KeywordDescription
operator[]Access bit
countCount bits set
sizeReturn size
testReturn bit value (true if 1, false if 0)
anyTest if any bit is set
noneTest if no bit is set
allTest if all bits are set

Bit Operations

OperationDescription
setSet all bits to 1
resetSet all bits to 0
flipToggle bit values
Comments (2)