C++ Basics: Measure the Bits Needed for an Unsigned Value
Use std::bit_width instead of floating-point logarithms when sizing an 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 bit-width-zero-case-demo.cpp:
#include <bit>
#include <iostream>
int main()
{
for (unsigned value : {0u, 1u, 7u, 8u, 255u, 256u}) {
std::cout << value << ": " << std::bit_width(value) << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic bit-width-zero-case-demo.cpp -o bit-width-zero-case-demo &&
./bit-width-zero-case-demoObserved output:
0: 0
1: 1
7: 3
8: 4
255: 8
256: 9Read the result
Seven fits in three binary digits, while eight needs four. Crossing from 255 to 256 similarly increases the width from eight to nine. Zero returns zero because it has no set bit, even though a human-readable binary representation would normally print a single zero.
Apply it carefully
Use an unsigned integer type. This is a property of the value, not the storage size of its type. If a display must reserve at least one digit, handle zero explicitly. Do not substitute floating-point logarithms near integer boundaries. This function does not round a capacity up to a power of two or include a sign bit.
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 -- bit-width-zero-case-demo.cpp bit-width-zero-case-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.