C++ Basics: Match Bitset Text to Bit Positions
Read a fixed-size bitset from binary text and distinguish printed order from numeric indexes.
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 bitset-text-index-order-demo.cpp:
#include <bitset>
#include <iostream>
#include <string>
int main()
{
std::bitset<8> flags{std::string{"10000001"}};
flags.set(1);
flags.reset(7);
std::cout << "Bits: " << flags << '\n';
std::cout << "Position zero: " << std::boolalpha << flags.test(0) << '\n';
std::cout << "Set count: " << flags.count() << '\n';
std::cout << "Numeric: " << flags.to_ulong() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic bitset-text-index-order-demo.cpp -o bitset-text-index-order-demo &&
./bitset-text-index-order-demoObserved output:
Bits: 00000011
Position zero: true
Set count: 2
Numeric: 3Read the result
Printed text places bit 7 on the left and bit 0 on the right. Setting position 1 adds the second-lowest bit; clearing position 7 removes the highest one. The final 00000011 has two set bits and a numeric value of 3.
Apply it carefully
A bitset has a compile-time size and does not grow. Validate external text length if you require exactly eight digits; the constructor is not an exact-width input validator. Invalid digit characters can throw invalid_argument. The checked test, set, and reset overloads taking a position throw out_of_range for an invalid index. Converting a much larger bitset with to_ulong can throw overflow_error when its value does not fit.
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 -- bitset-text-index-order-demo.cpp bitset-text-index-order-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.