std::has_single_bit
From 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) | 2の整数乗操作 |
[編集] 可能な実装
| 最初のバージョン |
|---|
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)); } |
| 2番目のバージョン |
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>のpublicメンバ関数) | |
| 特定のビットにアクセスする ( std::bitset<N>のpublicメンバ関数) |