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
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")); //00001010Indexing 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; // 0010Count 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); //trueCheck 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(); // trueCheck 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(); // falseCheck 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(); // falseSet 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(); //0101Bit access
| Keyword | Description |
|---|---|
| operator[] | Access bit |
| count | Count bits set |
| size | Return size |
| test | Return bit value (true if 1, false if 0) |
| any | Test if any bit is set |
| none | Test if no bit is set |
| all | Test if all bits are set |
Bit Operations
| Operation | Description |
|---|---|
| set | Set all bits to 1 |
| reset | Set all bits to 0 |
| flip | Toggle bit values |