bitset
This header is part of the general utility library.
std::bitset
template< std::size_t N>
class bitset;
The class template bitset represents a fixed-size sequence of N bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers. For the purpose of the string representation and of naming directions for shift operations, the sequence is thought of as having its lowest indexed elements at the right, as in the binary representation of integers.
-
Template parameters
- N: the number of bits to allocate storage for
-
Member types
- reference: proxy class representing a reference to a bit.
-
Member functions
| function |
definition |
| (constructor) |
constructs the bitset |
| operator== / operator!= (removed in C++20) |
compares the contents |
| operator[] |
access specific bit |
| test |
access specific bit |
| all/any/none |
checks if all, any or none of the bits are set to true |
| count |
returns the number of bits set to true |
| size |
returns the number of bits that the bitset holds |
| operator&= / operator|= / operator^= / operator~ |
performs binary AND, OR, XOR and NOT |
| opertaor<<= / opertaor>>= / opertaor<< / opertaor>> |
performs binary shift left and shift right |
| set |
sets bits to true or given value |
| reset |
sets bits to false |
| flip |
toggles the values of bits |
| to_string |
returns a string representation of the data |
| to_ulong |
returns an unsigned long integer representation of the data |
| to_ullong(C++11) |
returns an unsigned long long integer representation of the data |
| function |
definition |
| operator& / operator| / operator^ |
performs binary logic operations on bitsets |
| operator<< / operator>> |
performs stream input and output of bitsets |
#include <bitset>
#include <cassert>
#include <cstddef>
#include <iostream>
int main() {
typedef std::size_t length_t, position_t;
constexpr std::bitset<4> b1;
constexpr std::bitset<4> b2{0xA};
std::bitset<4> b3{"0011"};
std::bitset<8> b4{"ABAB", length_t(4), 'A',
'B'};
std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4
<< '\n';
b3 |= 0b0100;
assert(b3 == 0b0111);
b3 &= 0b0011;
assert(b3 == 0b0011);
b3 ^= std::bitset<4>{0b1100};
assert(b3 == 0b1111);
b3.reset();
assert(b3 == 0);
b3.set();
assert(b3 == 0b1111);
assert(b3.all() && b3.any() && !b3.none());
b3.flip();
assert(b3 == 0);
b3.set(position_t(1), true);
assert(b3 == 0b0010);
b3.set(position_t(1), false);
assert(b3 == 0);
b3.flip(position_t(2));
assert(b3 == 0b0100);
b3.reset(position_t(2));
assert(b3 == 0);
b3[2] = true;
assert(true == b3[2]);
assert(b3.count() == 1);
assert(b3.size() == 4);
assert(b3.to_ullong() == 0b0100ULL);
assert(b3.to_string() == "0100");
}