Intermediate Gotchas
The Bitset String That Runs Backward
the leftmost 1 lands in the highest bit
int main() {
std::bitset<8> mask{"10000000"};
std::cout << "bit 0: " << mask[0] << '\n';
std::cout << "bit 7: " << mask[7] << '\n';
}
Which indexed bit receives the string's first 1?
Why¶
The string constructor maps its rightmost character to bit zero, matching ordinary
left-to-right binary notation. operator[], however, uses numeric bit positions, where
zero is the least significant bit. Therefore the first character of an eight-character
string becomes bit seven. GCC 11.5 compiles this quietly under -Wall -Wextra.
The fix¶
Takeaway: read a bitset string like binary text, but index a bitset from the
right-hand, least-significant bit.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo