std::has_single_bit
ja.cppreference.net より
| ヘッダ <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 | - | 符号なし整数型の値 |
戻り値
true が x が2の整数乗である場合;そうでなければ false を返す。
注記
P1956R1
以前、この関数テンプレートの提案名は
ispow2
でした。
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_int_pow2
|
202002L
|
(C++20) | 整数の2の累乗 2 演算 |
実装例
template<typename T, typename ... U> concept neither = (!std::same_as<T, U> && ...); template<typename T> concept strict_unsigned_integral = std::unsigned_integral<T> && neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>; // 第一バージョン constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept { return x && !(x & (x - 1)); } // 第二バージョン constexpr bool has_single_bit(strict_unsigned_integral auto 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>
の公開メンバ関数)
|