Espacios de nombres
Variantes
Acciones

std::has_single_bit

De cppreference.com
< cpp‎ | numeric
 
 
 
Definido en el archivo de encabezado <bit>
template< class T >
constexpr bool has_single_bit(T x) noexcept;
(desde C++20)

Comprueba si x es una potencia entera de dos.

Esta sobrecarga solo participa en la resolución de sobrecargas si T es un tipo entero sin signo (es decir, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, o un tipo entero sin signo extendido).

Contenido

[editar] Valor de retorno

true si x es una potencia entera de dos; de lo contrario false.

[editar] Posible implementación

Primera versión
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;
}
Segunda versión
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; 
}

[editar] Ejemplo

#include <bit>
#include <bitset>
#include <iostream>
 
int main()
{
    std::cout << std::boolalpha;
    for (auto i = 0u; i < 10u; ++i) {
        std::cout << "has_single_bit( " << std::bitset<4>(i) << " ) = "
                  << std::has_single_bit(i) // `ispow2` antes de P1956R1
                  << '\n';
    }
}

Salida:

has_single_bit( 0000 ) = false
has_single_bit( 0001 ) = true
has_single_bit( 0010 ) = true
has_single_bit( 0011 ) = false
has_single_bit( 0100 ) = true
has_single_bit( 0101 ) = false
has_single_bit( 0110 ) = false
has_single_bit( 0111 ) = false
has_single_bit( 1000 ) = true
has_single_bit( 1001 ) = false

[editar] Véase también

(C++20)
Cuenta el número de bits 1 en un entero sin signo
(plantilla de función) [editar]
devuelve el número de bits puestos en true
Original:
returns the number of bits set to true
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(función miembro pública de std::bitset) [editar]
accede a poco específica
Original:
accesses specific bit
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(función miembro pública de std::bitset) [editar]