std::bit_ceil
From cppreference.com
| 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.
Parameters
| x | - | a value to compare with |
| Type requirements | ||
| T | - | must be an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type) in order to participate in overload resolution.
|
Return value
The smallest integral power of two that is not smaller than x.
Exceptions
Throws nothing.
Notes
Prior to P1956R1, the proposed name for this function template was ceil2.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_int_pow2 |
202002L |
(C++20) | Integral power-of-2 operations |
Possible implementation
See possible implementations in libstdc++ (gcc) and libc++ (clang).
template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);
template<std::unsigned_integral T>
requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr T bit_ceil(T x) noexcept
{
if (x == 0)
return T(1);
T bit_index = std::bit_width(T(x - 1));
if (bit_index >= std::numeric_limits<T>::digits)
std::unreachable(); // UB: result is not representable in T
return T(1) << bit_index;
}
|
Example
Run this code
#include <bit>
#include <print>
int main()
{
for (unsigned x{}; x != 0xA; ++x)
std::print("bit_ceil({:04b}) = {:05b}\n{}",
x, std::bit_ceil(x), std::has_single_bit(x) ? "\n" : "");
}
Output:
bit_ceil(0000) = 00001
bit_ceil(0001) = 00001
bit_ceil(0010) = 00010
bit_ceil(0011) = 00100
bit_ceil(0100) = 00100
bit_ceil(0101) = 01000
bit_ceil(0110) = 01000
bit_ceil(0111) = 01000
bit_ceil(1000) = 01000
bit_ceil(1001) = 10000
See also
(C++20) |
finds the largest integral power of 2 not greater than the given value (function template) |