Spec-Zone.ru › C++

std::bit_compress

Defined in header <bit>
template< class T >
constexpr T bit_compress( T x, T m ) noexcept;
(since C++29)

Selects the bits of x where m has a 1-bit, and packs them contiguously to the right. The remaining bits are 0.

This overload participates in overload resolution only if T is an unsigned integer type (that is, unsignedchar, unsignedshort, unsignedint, unsignedlong, unsignedlonglong, or an extended unsigned integer type).

Parameters

x - value of unsigned integer type
m - value of unsigned integer type

Return value

x with the bit-packing through the mask m applied.

Notes

The function is has the same result as the PEXT x86_64 and BEXT ARM instructions.

Feature-test macro Value Std Feature
__cpp_lib_bitops 202607L (C++29) Bit permutations

Possible implementation

template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);

template<std::unsigned_integral T>
    requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr T bit_compress(T x) noexcept
{
    T result = 0;
    for (int i = 0, j = 0; i < std::numeric_limits<T>::digits; ++i)
    {
        bool mask_bit = (m >> i) & 1;
        result |= (mask_bit & (x >> i)) << j;
        j += mask_bit;
    }
    return result;
}

Example

#include <bit>
#include <cstdint>

static_assert(
    std::bit_compress(
        std::uint16_t{0xABCD}, // source
        std::uint16_t{0x0F0F}) // mask
    ==  std::uint16_t{0x00BD}  // result
);
static_assert(
    std::bit_compress(
        std::uint8_t{0b0100'1001}, // source
        std::uint8_t{0b1100'1100}) // mask
    ==  std::uint8_t{0b0000'0110}  // result
);

int main() {}

See also

bit_expand
(C++29)
expands bits from an operand using a mask (PDEP)
(function template)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/numeric/bit_compress

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API