Skip to content
C++: Check a bit position with bitset test

C++: Check a bit position with bitset test

November 12, 2026

When a bit position comes from outside a fixed mask, std::bitset::test provides checked access. It throws std::out_of_range if the position is at least the bit count.

Prepare a scratch directory

Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save as cpp-bitset-test-checked-position.cpp:

#include <cassert>
#include <bitset>
#include <cstddef>
#include <iostream>
#include <stdexcept>

int main() {
    const std::bitset<8> flags{0b00001010};
    std::cout << std::boolalpha;
    for (std::size_t position : {std::size_t{1}, std::size_t{7}, std::size_t{8}}) {
        try {
            const bool enabled = flags.test(position);
            std::cout << position << ": " << enabled << '\n';
        } catch (const std::out_of_range&) {
            std::cout << position << ": out of range\n";
        }
    }
    assert(flags.test(1) && !flags.test(7));
}

Compile and run:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-bitset-test-checked-position.cpp -o cpp-bitset-test-checked-position &&
./cpp-bitset-test-checked-position

Observed output:

1: true
7: false
8: out of range

How it works

Position 1 selects the second least significant bit. Position 7 is the last valid position in this eight-bit mask; 8 is outside it. Reading into a local variable before printing keeps the failure line complete even when test throws.

Limits and choices

Do not use operator[] as a portable checked replacement. Validate signed input before converting it to std::size_t, especially if negative values have a separate meaning. The bitset size is fixed at compile time, and this example does not parse or validate an external numeric string.

The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.

Clean up

rm -- cpp-bitset-test-checked-position.cpp cpp-bitset-test-checked-position
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining files before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on