Namespaces
Variants
Views
Actions

std::bit_ceil

From cppreference.com
< cpp‎ | numeric
Defined in header <bit>
template< class T >
constexpr T bit_ceil(T x);
(since C++20)

Calculates the smallest integral power of two that is not smaller than x. If that value is not representable in T, the behavior is undefined.

This function is constexpr only if the result is representable in T.

This overload only participates in overload resolution if T is an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type).

Contents

[edit] Parameters

x - values of unsigned integer type

[edit] Return value

The smallest integral power of two that is not smaller than x.

[edit] Exceptions

(none)

[edit] Possible implementation

template <std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char> &&
             !std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
             !std::same_as<T, char32_t> && !std::same_as<T, wchar_t> 
constexpr T bit_ceil(T x)
{
    if (x != 0)
        return T{1} << std::bit_width(x - 1);
    return 1;
}

[edit] Example

#include <bit>
#include <bitset>
#include <iostream>
 
auto main() -> int
{
    using bin = std::bitset<8>;
 
    for (unsigned x{0}; x != 10; ++x)
    {
        auto const z = std::bit_ceil(x); // `ceil2` before P1956R1
 
        std::cout << "bit_ceil(" << bin(x) << ") = " << bin(z) << '\n';
    }
}

Output:

bit_ceil(00000000) = 00000001
bit_ceil(00000001) = 00000001
bit_ceil(00000010) = 00000010
bit_ceil(00000011) = 00000100
bit_ceil(00000100) = 00000100
bit_ceil(00000101) = 00001000
bit_ceil(00000110) = 00001000
bit_ceil(00000111) = 00001000
bit_ceil(00001000) = 00001000
bit_ceil(00001001) = 00010000

[edit] See also

(C++20)
finds the largest integral power of two not greater than the given value
(function template) [edit]