std::has_single_bit_C++中文网
| template< class T > |
(C++20 起) | |
检查 x 是否为二的整数次幂。
此重载仅若 T 为无符号整数类型(即 unsigned char 、 unsigned short 、 unsigned int 、 unsigned long 、 unsigned long long 或扩展无符号整数类型)才参与重载决议。
返回值
若 x 为二的整数次幂则为 true ;否则为 false 。
可能的实现
template <std::unsigned_integral T> requires !std::same_as<T, bool> && !std::same_as<T, char> constexpr bool has_single_bit(T x) noexcept { return x != 0 && (x & (x - 1)) == 0; }
示例
#include <bit> #include <iostream> int main() { std::cout << std::boolalpha; for (auto i = 0u; i < 10u; ++i) { std::cout << "has_single_bit(" << i << ") = " << std::has_single_bit(i) << '\n'; } }
输出:
has_single_bit(0) = false has_single_bit(1) = true has_single_bit(2) = true has_single_bit(3) = false has_single_bit(4) = true has_single_bit(5) = false has_single_bit(6) = false has_single_bit(7) = false has_single_bit(8) = true has_single_bit(9) = false