std::has_single_bit

来自cppreference.com
< cpp‎ | numeric
定义于头文件 <bit>
template< class T >
constexpr bool has_single_bit(T x) noexcept;
(C++20 起)

检查 x 是否为二的整数次幂。

此重载仅若 T 为无符号整数类型(即 unsigned charunsigned shortunsigned intunsigned longunsigned 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