C++ Bitsets give the programmer a set of bits as a data structure. Bitsets can be manipulated by using various binary operators such as logical AND, OR, XOR, and so on.

Bitset Constructors

  • any – returns true(1) if any bits are set else return false (0)
  • count – returns the number of set bits ie. how many bits are 1 in the binary representation of the given number.
  • flip – reverses the bitset
  • none – returns true (1)  if no bits are set else false (1) if any of the bits are set.
  • reset – sets bits to zero
  • set – sets bits
  • size – outputs the number of bits that the bitset can hold
  • test – return the value of a given bit
  • to_string – convert the bitset data to the string representation of the bitset.
    • like we have bitset 11001110 then to string it will be “11001110”.
  • to_ulong – returns an unsigned long integer representation of the bitset

Below is the implementation of some of this function and rest can be used in the same way.

#include <bitset>
#include <iostream>
using namespace std;

int main() {
    // creates a bitset that is 8 bits long.
    bitset<8> bs;
    cout << "Size of bs: " << bs.size() << "\n";
    for (int i = 0; i < (int)bs.size(); i++) {
        cout << bs[i];
    }
    cout << "\n\n";

    // creating a bitset with default value.
    cout << "Printing bitset value from new bitset with default value.\n";
    bitset<8> dbs((long)131);
    for (int i = (int)dbs.size() - 1; i >= 0; i--) {
        cout << dbs[i];
    }
    cout << "\n\n";

    // converting bitset to string of bits.
    string bits = dbs.to_string();
    cout << "The dbs bits in string: " << bits << "\n\n";

    // converting bitset to unsigned long.
    long num = dbs.to_ulong();
    cout << "The dbs bits in unsigned long: " << num << "\n\n";

    cout << "The number of bits that the bitset can hold: " << dbs.size()
         << "\n\n";

    // To get the value of bit at given position,let us say at position 2 in
    // dbs.
    cout << "The value of bits at position 2 in dbs: " << dbs.test(2) << "\n";

    return 0;
}

Output:

Size of bs: 8
00000000

Printing bitset value from new bitset with default value.
10000011

The dbs bits in string: 10000011

The dbs bits in unsigned long: 131

The number of bits that the bitset can hold: 8

The value of bits at position 2 in dbs: 0

If you find any error or have any query then feel free to comment.

Thank You
Happy Coding!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments