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
が2の整数乗であれば true、そうでなければ false。
[編集] 実装例
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 != 0 && (x & (x - 1)) == 0; } |
[編集] 例
Run this code
#include <bit> #include <bitset> #include <iostream> int main() { using bin = std::bitset<8>; std::cout << std::boolalpha; for (auto i = 0u; i < 10u; ++i) { std::cout << "has_single_bit(" << bin(i) << ") = " << std::has_single_bit(i) // `ispow2` before P1956R1 << '\n'; } }
出力:
has_single_bit(00000000) = false has_single_bit(00000001) = true has_single_bit(00000010) = true has_single_bit(00000011) = false has_single_bit(00000100) = true has_single_bit(00000101) = false has_single_bit(00000110) = false has_single_bit(00000111) = false has_single_bit(00001000) = true has_single_bit(00001001) = false