Using the bit manipulation utilities
In the previous recipes, we have seen how to use
std::vector<bool> to work with fixed and variable sequences of bits. There are, however, situations when we need to manipulate or process individual or multiple bits of an unsigned integral value. This includes operations such as counting or rotating bits. The C++20 standard provides a set of utility functions for bit manipulation as part of the numeric library. In this recipe, we will learn what they are and how to use these utilities.
The function templates discussed in this recipe are all available in the
std namespace in the new C++20 header
How to do it…
Use the following function templates to manipulate bits of unsigned integral types:
- If you need to perform a circular shift, use
std::rotl<T>()for left rotation and
std::rotr<T>()for right rotation:
unsigned char n = 0b00111100; auto vl1...