Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::bitset: a fixed sequence of bits

std::bitset<N> stores exactly N bits and provides bit operations, counting, and conversions without dynamic sizing.

Version: C++23

Syntax

template<std::size_t N>
class bitset;

std::bitset<N> bits{value};

std::bitset<N> from <bitset> stores a bit count fixed at compile time. Position 0 is the least-significant bit; set, reset, flip, test, count, logical operators, and shifts are available. Mutable operator[] returns a proxy object, not a real bool&.

The string constructor throws std::out_of_range when pos > size and validates all rlen = min(n, size - pos) characters, throwing std::invalid_argument for a symbol other than zero or one. Only the first M = min(N, rlen) characters supply bits, with the last of that portion mapping to bit 0. test(pos), set(pos), reset(pos), and flip(pos) throw std::out_of_range when pos >= N; operator[] requires a valid position. to_ulong and to_ullong throw std::overflow_error when the value is not representable.

The size cannot change at runtime; a dynamic bit count needs another data structure. bitset<0> is valid: size() and count() are zero, any() is false, and all() and none() are true. Operations on different N are not directly interchangeable.

Examples

#include <bitset>
#include <iostream>

int main() {
    const std::bitset<8> bits{0b00101101};
    std::cout << bits << ' ' << bits.count() << ' ' << bits.test(0) << '\n';
}

Result

00101101 4 1

std::bitset → 00101101 4 1

Sources