名稱空間
變體
操作

std::has_single_bit

來自 cppreference.com
< cpp‎ | 數值
 
 
 
位操作
(C++20)
(C++23)
2 的整數次冪
has_single_bit
(C++20)
(C++20)
(C++20)
(C++20)
旋轉
(C++20)
(C++20)
計數
(C++20)
(C++20)
(C++20)
位元組序
(C++20)
 
定義於標頭檔案 <bit>
template< class T >
constexpr bool has_single_bit( T x ) noexcept;
(C++20 起)

檢查 x 是否是 2 的整數次冪。

此過載僅在 T 為無符號整數型別(即 unsigned charunsigned shortunsigned intunsigned longunsigned long long 或擴充套件無符號整數型別)時參與過載決議。

目錄

[編輯] 引數

x - 無符號整數型別的值

[編輯] 返回值

x 是 2 的整數次冪,則為 true;否則為 false

[編輯] 註解

P1956R1 之前,此函式模板的擬議名稱為 ispow2

特性測試 標準 特性
__cpp_lib_int_pow2 202002L (C++20) 整數次冪操作

[編輯] 可能實現

第一版
template<std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char> &&
             !std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
             !std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr bool has_single_bit(T x) noexcept
{
    return x && !(x & (x - 1));
}
第二版
template<std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char> &&
             !std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
             !std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr bool has_single_bit(T x) noexcept
{
    return std::popcount(x) == 1;
}

[編輯] 示例

#include <bit>
#include <bitset>
#include <cmath>
#include <iostream>
 
int main()
{
    for (auto u{0u}; u != 0B1010; ++u)
    {
        std::cout << "u = " << u << " = " << std::bitset<4>(u);
        if (std::has_single_bit(u))
            std::cout << " = 2^" << std::log2(u) << " (is power of two)";
        std::cout << '\n';
    }
}

輸出

u = 0 = 0000
u = 1 = 0001 = 2^0 (is power of two)
u = 2 = 0010 = 2^1 (is power of two)
u = 3 = 0011
u = 4 = 0100 = 2^2 (is power of two)
u = 5 = 0101
u = 6 = 0110
u = 7 = 0111
u = 8 = 1000 = 2^3 (is power of two)
u = 9 = 1001

[編輯] 參閱

(C++20)
計算無符號整數中 1 位的數量
(函式模板) [編輯]
返回被設定為 true 的位數
(std::bitset<N> 的公開成員函式) [編輯]
訪問特定位
(std::bitset<N> 的公開成員函式) [編輯]