std::ispow2
From cppreference.com
| Defined in header <bit>
|
||
| template< class T > constexpr bool ispow2(T x) noexcept; |
(since C++20) | |
Checks if x is an integral power of two.
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).
[edit] Return value
true if x is an integral power of two; otherwise false.
[edit] Possible implementation
template <std::unsigned_integral T> requires !std::same_as<T, bool> && !std::same_as<T, char> constexpr bool ispow2(T x) noexcept { return x != 0 && (x & (x - 1)) == 0; } |
[edit] Example
Run this code
#include <bit> #include <iostream> int main() { std::cout << std::boolalpha; for (auto i = 0u; i < 10u; ++i) { std::cout << "ispow2(" << i << ") = " << std::ispow2(i) << '\n'; } }
Output:
ispow2(0) = false ispow2(1) = true ispow2(2) = true ispow2(3) = false ispow2(4) = true ispow2(5) = false ispow2(6) = false ispow2(7) = false ispow2(8) = true ispow2(9) = false

