Codectionary / Developer documentation / C++

C++ std::bitset flags

bitset holds a fixed number of bits and supports named operations such as set, reset, test and count. It is useful for compact fixed-size feature or availability masks. This example uses C++11 or later.

Syntax

std::bitset<8> flags; flags.set(2); bool enabled = flags.test(2);

Examples

C++ std::bitset flags

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <bitset>
#include <iostream>
int main() {
    std::bitset<8> permissions;
    permissions.set(0);
    permissions.set(2);
    std::cout << permissions << '\n';
    std::cout << permissions.count() << '\n';
}
  1. Output: 00000101, then 2. Bit index zero is the rightmost bit in the displayed representation.

Best practices

  • Use named constants for flag positions. test provides checked access; keep indices inside the fixed bit count.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading