std::bitset::test(3)
β¨ std::bitset::test β¨
okay bestie, welcome to the std::bitset::test(3) page from the C++ Standard Libary corner of cppreference π this is literally the safe little bit-checker with a bounds check, and it's giving "trust me bestie, I checked" energy π
π NAME π
std::bitset::test - std::bitset::test (yes bestie, that's the whole name, iconic π
)
π¦ Synopsis π¦
bool test( std::size_t pos ) const; (constexpr since C++23)
okay so this returns the value of the bit at the position pos (counting from 0) β¨
unlike operator[], it performs a bounds check and throws std::out_of_range if pos does not correspond to a valid position in the bitset. like, it's not just vibing, it's actually checking the vibes first π
π Parameters π
posβ position of the bit to return (counting from 0) π«Ά
πΈ Return value πΈ
true if the requested bit is set, false otherwise. periodt. β¨
π₯ Exceptions π₯
std::out_of_range if pos does not correspond to a valid position within the bitset. no cap, it will throw π
π Example π
the page says // Run this code, so literally run it, bestie π
#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))
++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';
else
std::cout << "no set bits\n";
try
{
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, slay:
The first set bit is at index 4
Exception: bitset::test: __position (which is 666) >= _Nb (which is 666)
π See also π
operator[]β accesses specific bit (public member function) πpopcountβ counts the number of 1 bits in an unsigned integer (C++20) (function template) β¨has_single_bitβ checks if a number is an integral power of 2 (C++20) (function template) π
and that's the whole page, bestie π«Ά source/version/date realness: this came from http://cppreference.com, dated 2024.06.10, and the page is literally std::bitset::test(3) π bye bestie, go test those bits responsibly π
β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms