Skip to content

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?

Answer
bit 0: 0
bit 7: 1

The string's first character is the most significant bit.

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

std::bitset<8> mask{0b10000000};

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

Open in Compiler Explorer ↗ Quiz this entry