C++ Basics: Rotate an Eight-Bit Pattern Without Losing Bits
Use std::rotl and std::rotr to wrap bits around a fixed-width unsigned value.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as rotl-fixed-width-demo.cpp:
#include <bit>
#include <cstdint>
#include <iostream>
#include <limits>
int main()
{
static_assert(std::numeric_limits<std::uint8_t>::digits == 8);
const std::uint8_t value = 0b10000001;
std::cout << "Left one: " << unsigned(std::rotl(value, 1)) << '\n';
std::cout << "Right one: " << unsigned(std::rotr(value, 1)) << '\n';
std::cout << "Full turn: " << unsigned(std::rotl(value, 8)) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic rotl-fixed-width-demo.cpp -o rotl-fixed-width-demo &&
./rotl-fixed-width-demoObserved output:
Left one: 3
Right one: 192
Full turn: 129Read the result
Rotating 10000001 left gives 00000011, or 3. Rotating it right gives 11000000, or 192. A rotation by the full eight-bit width returns the original value, 129. Converting the result to unsigned makes stream output numeric rather than character-like.
Apply it carefully
Rotation uses the width of the unsigned argument type. Widening the value before rotating changes the operation. Exact-width std::uint8_t is available on the tested platform but is optional in C++. Rotation counts wrap by the width, and a negative count rotates in the opposite direction. Plain shifts have different rules and do not preserve bits shifted out of the value.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- rotl-fixed-width-demo.cpp rotl-fixed-width-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.