# std::bitset<N>::count

> C++ Atlas: `cppatlas.com/w/cpp/utility/bitset/count` | Source: https://en.cppreference.com/w/cpp/utility/bitset/count | Domain: Utility | Standards: C++11, C++20, C++23

Returns the number of bits that are set to true.

## Official Specification Summary (cppreference)

```cpp
std::size_t count() const; // (noexcept since C++11) (constexpr since C++23)
```

Returns the number of bits that are set to `true`.

### Return value

Number of bits that are set to `true`.

### Example

```cpp
#include <bitset>
#include <iostream>

constexpr auto popcount(unsigned x) noexcept
{
    unsigned num{};
    for (; x; ++num, x &= (x - 1));
    return num;
};
static_assert(popcount(0b101010) == std::bitset<8>{0b101010}.count());

int main()
{
    std::bitset<8> b("00010010");
    std::cout << "Initial value: " << b << '\n';

    // Find the first unset bit
    std::size_t idx = 0;
    while (idx < b.size() && b.test(idx))
        ++idx;

    // Continue setting bits until half the bitset is filled
    while (idx < b.size() && b.count() < b.size() / 2)
    {
        b.set(idx);
        std::cout << "Setting bit " << idx << ": " << b << '\n';
        while (idx < b.size() && b.test(idx))
            ++idx;
    }
}
```

Output:

```text
Initial value: 00010010
Setting bit 0: 00010011
Setting bit 2: 00010111
```

### See also

- [`size`](https://en.cppreference.com/w/cpp/utility/bitset/size): returns the number of bits that the bitset holds (public member function)
- [`popcount`](https://en.cppreference.com/w/cpp/numeric/popcount) (C++20): counts the number of `1` bits in an unsigned integer (function template)

---
Attribution: content from https://en.cppreference.com/w/cpp/utility/bitset/count (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.