c-plus-plus
  1. c-plus-plus-bitset

C++ STL Tutorial - Bitset

The C++ STL bitset is a specialized container class that holds bits (boolean values) and provides an array-like interface to access them. It is a fixed-size container that can hold a specified number of bits, and is especially useful for working with large bitmaps and bit arrays.

Syntax

bitset<N> bitset_variable;      // create a bitset of size N
bitset<N> bitset_variable(value);  // create a bitset initialized with a value
bitset<N> bitset_variable(string); // create a bitset initialized with a binary string

Where N is the number of bits in the bitset.

Example

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

int main() {
    bitset<5> bits1;  // create a bitset of 5 bits
    bitset<5> bits2(13);  // create a bitset initialized with a value
    bitset<5> bits3("10110");  // create a bitset initialized with a binary string

    cout << bits1 << endl;  // prints 00000
    cout << bits2 << endl;  // prints 01101
    cout << bits3 << endl;  // prints 10110

    return 0;
}

Output

00000
01101
10110

Explanation

In the above example, we have created three different bitsets of size 5 bits, one with the default constructor, one with an integer value, and one with a binary string. We then output their various states using the overloaded stream insertion operator (<<).

Use

The STL bitset is used for a variety of tasks where arrays of bits are needed. Some common use cases include:

  • Implementing bit maps, where a large number of bits need to be represented efficiently.
  • Working with binary data, where individual bits need to be accessed or modified.
  • Implementing checksums and other binary algorithms that require bit-level manipulation.

Important Points

  • The size of a bitset is determined at compile-time and cannot be changed at runtime.
  • Bitset elements can be accessed using the [] operator.
  • Bitset elements can be set using the set() method, and cleared using the reset() method.
  • Bitset elements can be flipped using the flip() method.
  • Common bitwise operations (AND, OR, XOR, NOT) are provided as overloaded operators.

Summary

In summary, the C++ STL bitset is a useful container class for working with arrays of bits. It is useful for a wide range of tasks, including implementing bit maps and working with binary data. Bit manipulation is performed using a variety of methods, including the [] operator, the set() and reset() methods, and the overloaded bitwise operators.

Published on: