Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Bit operations

Use case

Portable bit manipulation.

Explanation

<bit> header provides portable bit operations. Before C++20, for example, we had to use __builtin_popcount(x) (gcc/clang) vs __popcnt(x) (MSVC).

Code

#include <bit>
#include <cstdint>
#include <iostream>

int main() {
  uint32_t flags = 0b1010'0000'0000'0000'0000'0000'1000'0000;
  // https://en.cppreference.com/w/cpp/header/bit.html
  std::cout << "popcount: " << std::popcount(flags) << "\n";
  std::cout << "has_single_bit: " << std::has_single_bit(flags) << "\n";
  std::cout << "countl_zero: " << std::countl_zero(flags) << "\n";
  std::cout << "countr_zero: " << std::countr_zero(flags) << "\n";
  std::cout << "bit_width: " << std::bit_width(flags) << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/bit-operations
popcount: 3
has_single_bit: 0
countl_zero: 0
countr_zero: 7
bit_width: 32