C++ Basics: Check Whether a Value Is a Power of Two
Use std::has_single_bit for unsigned power-of-two checks, including the zero boundary.
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 has-single-bit-power-of-two-demo.cpp:
#include <array>
#include <bit>
#include <iostream>
int main()
{
constexpr std::array<unsigned, 6> sizes{0, 1, 2, 3, 8, 12};
std::cout << std::boolalpha;
for (unsigned size : sizes) {
std::cout << size << ": " << std::has_single_bit(size) << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic has-single-bit-power-of-two-demo.cpp -o has-single-bit-power-of-two-demo &&
./has-single-bit-power-of-two-demoObserved output:
0: false
1: true
2: true
3: false
8: true
12: falseRead the result
One, two, and eight each have exactly one set bit. Zero has none, while three and twelve have two. Zero therefore fails without a separate special-case expression.
Apply it carefully
Pass an unsigned integer type. If an input begins as a signed number, validate it before converting. This test does not round a requested size, impose a maximum allocation size, or prove that an address is aligned.
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 -- has-single-bit-power-of-two-demo.cpp has-single-bit-power-of-two-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.