std:: has_single_bit
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
(C++20)
|
||||
|
(C++23)
|
||||
| Integral powers of 2 | ||||
|
has_single_bit
(C++20)
|
||||
|
(C++20)
|
||||
|
(C++20)
|
||||
|
(C++20)
|
||||
| Rotating | ||||
|
(C++20)
|
||||
|
(C++20)
|
||||
| Counting | ||||
|
(C++20)
|
||||
|
(C++20)
|
||||
|
(C++20)
|
||||
|
(C++20)
|
||||
|
(C++20)
|
||||
| Endian | ||||
|
(C++20)
|
|
Definiert im Header
<bit>
|
||
|
template
<
class
T
>
constexpr bool has_single_bit ( T x ) noexcept ; |
(seit C++20) | |
Überprüft, ob x eine ganzzahlige Zweierpotenz ist.
Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn
T
ein vorzeichenloser Ganzzahltyp ist (also
unsigned
char
,
unsigned
short
,
unsigned
int
,
unsigned
long
,
unsigned
long
long
oder ein erweiterter vorzeichenloser Ganzzahltyp).
Inhaltsverzeichnis |
Parameter
| x | - | Wert des vorzeichenlosen Ganzzahltyps |
Rückgabewert
true wenn x eine ganzzahlige Zweierpotenz ist; andernfalls false .
Hinweise
Vor
P1956R1
war der vorgeschlagene Name für diese Funktionsvorlage
ispow2
.
| Feature-Test Makro | Wert | Std | Funktion |
|---|---|---|---|
__cpp_lib_int_pow2
|
202002L
|
(C++20) | Ganzzahlige Zweierpotenz- 2 Operationen |
Mögliche Implementierung
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>; // Erste Version constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept { return x && !(x & (x - 1)); } // Zweite Version constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept { return std::popcount(x) == 1; } |
Beispiel
#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'; } }
Ausgabe:
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
Siehe auch
|
(C++20)
|
zählt die Anzahl der
1
Bits in einer vorzeichenlosen Ganzzahl
(Funktionsschablone) |
|
gibt die Anzahl der auf
true
gesetzten Bits zurück
(öffentliche Elementfunktion von
std::bitset<N>
)
|
|
|
greift auf bestimmtes Bit zu
(öffentliche Elementfunktion von
std::bitset<N>
)
|