std::bit_compress
From cppreference.com
| Defined in header <bit>
|
||
template< class T >
constexpr T bit_compress( T x, T mask ) noexcept;
|
(since C++29) | |
Selects the bits of x where mask has a 1-bit, and packs them contiguously to the right. The remaining bits are 0.
Parameters
| x | - | the source value for packing |
| mask | - | the bit-mask for packing |
| Type requirements | ||
| T | - | must be an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type) in order to participate in overload resolution.
|
Return value
x with the bit-packing through the mask mask 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 source, T mask) noexcept
{
T result{};
for (T source_mask{1}, result_mask{1}; source_mask; source_mask <<= 1)
if (source_mask & mask)
result |= source_mask & mask & source ? result_mask : 0,
result_mask <<= 1;
return result;
}
|
Example
Run this code
#include <bit>
#include <cstdint>
static_assert(
std::bit_compress(
std::uint16_t{0xABCD}, // source
std::uint16_t{0x0F0F}) // mask
== std::uint16_t{0x00BD} // result
and
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
(C++29) |
expands bits from an operand using a mask (PDEP) (function template) |
External links
| 1. | What is a fast fallback algorithm which emulates PDEP and PEXT in software? — SO |
| 2. | Reference implementation of C++26/29 bit permutation functions — github.com |
| 3. | ZP7: Zach's Peppy Parallel-Prefix-Popcountin' PEXT/PDEP — github.com |
| 4. | Henry S. Warren, Jr. Hacker's Delight, 2nd Edition, 2013, pp.150–161. |