< cpp‎ | utility‎ | bitset
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Elementary string conversions
bool test( std::size_t pos ) const;
(constexpr since C++23)

Returns the value of the bit at the position pos (counting from 0).

Unlike operator[], performs a bounds check and throws std::out_of_range if pos does not correspond to a valid position in the bitset.


[edit] Parameters

pos - position of the bit to return (counting from 0)

[edit] Return value

true if the requested bit is set, false otherwise.

[edit] Exceptions

std::out_of_range if pos does not correspond to a valid position within the bitset.

[edit] Example

#include <bit>
#include <bitset>
#include <cassert>
#include <iostream>
#include <stdexcept>
int main()
    std::bitset<10> b1("1111010000");
    std::size_t idx = 0;
    while (idx < b1.size() && !b1.test(idx))
    assert(static_cast<int>(idx) == std::countr_zero(b1.to_ulong()));
    if (idx < b1.size())
        std::cout << "The first set bit is at index " << idx << '\n';
        std::cout << "no set bits\n";
        std::bitset<0B10'1001'1010> bad;
        if (bad.test(bad.size()))
            std::cout << "Expect unexpected!\n";
    catch (std::out_of_range const& ex)
        std::cout << "Exception: " << ex.what() << '\n';

Possible output:

The first set bit is at index 4
Exception: bitset::test: __position (which is 666) >= _Nb (which is 666)

[edit] See also

accesses specific bit
(public member function) [edit]
counts the number of 1 bits in an unsigned integer
(function template) [edit]
checks if a number is an integral power of two
(function template) [edit]