wiki:hpp-bit
<bit>
<bit> provides bit manipulation utilities introduced in C++20: std::popcount (count set bits), std::countl_zero / std::countr_zero (leading/trailing zeros), std::rotl / std::rotr (rotate), and std::byteswap.
These are thin wrappers around intrinsics like __builtin_popcount, providing portable, consistent semantics without writing assembly.
Example
This example demonstrates counting set bits, counting leading zeros, and rotating bits left, all on an integer value.
// compile: g++ -std=c++20 -o bitexample bitexample.cpp // run: ./bitexample // description: bit counting and rotation #include <bit> #include <iostream> int main() { unsigned int x = 0b11010011; std::cout << "popcount of " << x << ": " << std::popcount(x) << "\n"; std::cout << "leading zeros: " << std::countl_zero(x) << "\n"; std::cout << "rotl by 2: " << std::rotl(x, 2) << "\n"; return 0; }
wiki/hpp-bit.md · Last modified: by 127.0.0.1
