std::bitset<N>::test

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

Returns the value of the bit at the position pos.

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

Parameters

pos - position of the bit to return

Return value

true if the requested bit is set, false otherwise.

Exceptions

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

Example

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

Possible output:

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

See also

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