C++ Basics: Count Only the Flags in a Selected Mask
Combine a bit mask with std::popcount to count enabled options in one group.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
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 1Run the example
Save this as popcount-selected-flags-demo.cpp:
#include <bit>
#include <iostream>
int main()
{
const unsigned enabled = 0b10110100u;
const unsigned group = 0b00001111u;
std::cout << "All enabled: " << std::popcount(enabled) << '\n';
std::cout << "Group enabled: " << std::popcount(enabled & group) << '\n';
std::cout << "Empty: " << std::popcount(0u) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic popcount-selected-flags-demo.cpp -o popcount-selected-flags-demo &&
./popcount-selected-flags-demoObserved output:
All enabled: 4
Group enabled: 1
Empty: 0Read the result
The full value has four set bits. Applying the group mask retains only the low four positions, where one bit is set. A zero value has no enabled bits. The result counts positions; it does not return the numeric sum of the masks.
Apply it carefully
The input must be an unsigned integer type. Assign one distinct bit to each independent boolean option before interpreting the count as a number of options. Multi-bit encoded fields, such as a three-bit mode number, are not three independent flags. Mask out reserved or unrelated bits first when they should not contribute.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- popcount-selected-flags-demo.cpp popcount-selected-flags-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.