std::bitset explained with simple example

A Bitset is a standard template library class provided by C++ which can be used to define a fixed length sequence of bits. A value of zero indicates bit is unset whereas 1 indicates bit is set.
This class provides similar functionality as array of Boolean values in more space efficient way. There are lot of useful memory functions also provided by the library which can be used by the programmers to use it directly.

Let’s have a look into std::bitset template class definition.

template <size_t N> class bitset;
Where N = length of bitset (in bits).

Initialization

  • Initialize an empty bitset.
    • Constructor — bitset( );
    • Usage — std::bitset<4> b1;
  • Initialize an bitset with some value.
    • Constructor — bitset(unsigned long bits);
    • Usage — std::bitset<4> b2{0xA};
  • Initialize an bitset from string values starting at certain location.
    • Constructor — explicit bitset(const string &s, size_t i = 0, size_t num = npos);
    • Usage – bitset<4> b5{“0110”, 4};
  • Initialize an bitset from string values other than 0 and 1.
    • Constructor — template< class CharT >
      explicit bitset( const CharT* str,
                      typename std::basic_string<CharT>::size_type
                           n = std::basic_string<CharT>::npos,
                       CharT zero = CharT(‘0’),
                       CharT one = CharT(‘1’) );
    • Usage — std::bitset<8> b4{“CDCD”, 4, /*0:*/’C’, /*1:*/’D’};

Member functions

Let’s look into the member functions that are available with std::bitset class.

Member functionsUsage
bool any( ) const;Returns true if any bit in bitset is 1 else false.
size_type count( ) const;Returns the number of bits that are set to 1.
bitset<N> &flip( );Reverse all the bits in the bitset.
bitset<N> &flip(size_t i);Reverse the ith bit in the bitset.
bool none( ) const;Returns true if none of the bit in bitset is set.
bool all() constReturns true if all of the bit in bitset are set.
bool operator !=(const bitset<N> &op2) const;Returns true if invoking bitset is different from RHS.
bool operator ==(const bitset<N> &op2) const;Returns true if invoking bitset is same as RHS.
bitset<N> &operator &=(const bitset<N> &op2);Perform bitwise AND operation between invoking and passed bitset in op2 and save the result in invoking bitset.
bitset<N> &operator ^=(const bitset<N> &op2);Perform bitwise XOR operation between invoking and passed bitset in op2 and save the result in invoking bitset.
bitset<N> &operator |=(const bitset<N> &op2);Perform bitwise OR operation between invoking and passed bitset in op2 and save the result in invoking bitset.
bitset<N> &operator ~( ) const;Reverse the state of all bits.
bitset<N> &operator <<=(size_t num);Left shift each bit in bitset by num positions.
bitset<N> &operator >>=(size_t num);Right shift each bit in bitset by num positions.
bitset<N> &reset( );Clears all bits in the bitset.
bitset<N> &reset(size_t i);Clears bit in the ith position in the bitset.
bitset<N> &set( );Sets all bits in the bitset.
bitset<N> &set(size_t i, int val = 1);Sets bit in the ith position with value “val” in the bitset.
size_t size( ) const;Returns the size of bitset.
bool test(size_t i) const;Returns the bit state of the bit in bitset at ith position.
string to_string( ) const;Returns a string that shows bitset value.
unsigned long to_ulong( ) const;Returns a unsigned long long number indicating bitset value.
std::bitset member function

Let’s have a look into a sample program which uses above function to showcases its usage.

#include <bitset>
#include <cstddef>
#include <cassert>
#include <iostream>

using namespace std;

int main() {
    bitset<4> b1;
    constexpr bitset<4> b2{0xC};
    bitset<4> b3{"0111"};
    bitset<8> b4{"CDCD", 4, /*0:*/'C', /*1:*/'D'};
    bitset<4> b5{"0110", 4};

    // bitsets can be printed out to a stream:
    cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << "; b5:" << b5 << endl;
    cout << "any bit set ? b1: " << b1.any() << "; b2: " << b2.any() << endl;
    if (b1.none())
        cout << "b1 has none of the bit set !!" << endl;
    cout << "No. of bits set, b3: " << b3.count() << "; b4: " << b4.count() << endl;
    b1.flip();
    b3.flip(1);
    cout << "b1:" << b1 << "; b3:" << b3 << endl;
    if (b1.all())
        cout << "b1 has all of the bit set !!" << endl;
    cout << "Check b1 != b2 -- " << (b1 != b2) << "; b1 == b2 -- " << (b1 == b2) << endl;
    b1 &= b2;
    b3 ^= b2;
    b5 |= b2;
    cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << "; b5:" << b5 << endl;
    b1.reset();
    b3.reset(3);
    b5.set();
    b4.set(3);
    b4.set(0, 0);
    cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << "; b5:" << b5 << endl;
    b1 = ~b1;
    b3 <<= 4;
    b4 >>= 4;
    cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << "; b5:" << b5 << endl;
    cout << "b2 size: " << b2.size() << ", Contents -- ";
    for (int i = 0;i < b2.size(); i++) {
        cout << b2[i] << " " ;
    }
    cout << endl;
    cout << "is 2nd bit set in b2 ? " << b2.test(2) << endl;
    string str = b2.to_string();
    unsigned long t = b2.to_ulong();
    cout << "b2 bitset -- " << b2 << ", string -- " << str << ", long -- " << t << endl;
	return 0;
}

Let’s look into the output of above program.

b1:0000; b2:1100; b3:0111; b4:00000101; b5:0110
any bit set ? b1: 0; b2: 1
b1 has none of the bit set !!
No. of bits set, b3: 3; b4: 2
b1:1111; b3:0101
b1 has all of the bit set !!
Check b1 != b2 -- 1; b1 == b2 -- 0
b1:1100; b2:1100; b3:1001; b4:00000101; b5:1110
b1:0000; b2:1100; b3:0001; b4:00001100; b5:1111
b1:1111; b2:1100; b3:0000; b4:00000000; b5:1111
b2 size: 4, Contents -- 0 0 1 1 
is 2nd bit set in b2 ? 1
b2 bitset -- 1100, string -- 1100, long -- 12

Leave a Reply

Your email address will not be published. Required fields are marked *