std::has_single_bit
來自 cppreference.com
定義於標頭檔案 <bit> |
||
template< class T > constexpr bool has_single_bit( T x ) noexcept; |
(C++20 起) | |
檢查 x 是否是 2 的整數次冪。
此過載僅在 T
為無符號整數型別(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned 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> 的公開成員函式) |