std::ispow2
| 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
#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

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
