Skip to content
C++ Basics: Find the Largest Power of Two Within a Budget

C++ Basics: Find the Largest Power of Two Within a Budget

November 8, 2026

Use bit_floor to choose a power-of-two capacity that does not exceed an unsigned budget.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus 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 1

Run the example

Save this as bit-floor-capacity-budget-demo.cpp:

#include <array>
#include <bit>
#include <iostream>

int main()
{
    for (unsigned budget : std::array<unsigned, 5>{0, 1, 15, 16, 17}) {
        const unsigned capacity = std::bit_floor(budget);
        std::cout << budget << " -> " << capacity << '\n';
    }
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic bit-floor-capacity-budget-demo.cpp -o bit-floor-capacity-budget-demo &&
./bit-floor-capacity-budget-demo

Observed output:

0 -> 0
1 -> 1
15 -> 8
16 -> 16
17 -> 16

Read the result

Exact powers of two remain unchanged, 15 rounds down to 8, and 17 rounds down to 16. A zero budget produces zero, which is not a power of two.

Apply it carefully

bit_floor takes an unsigned integer type, excluding bool and the character types that the standard does not classify as unsigned integer types. Check for zero before using its result as a divisor or a required positive capacity. It rounds down; it does not guarantee enough storage for the original budget of items.

The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- bit-floor-capacity-budget-demo.cpp bit-floor-capacity-budget-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on