std::bit_compress
来自 zh.cppreference.net
| 定义于头文件 <bit>
|
||
template< class T >
constexpr T bit_compress( T x, T m ) noexcept;
|
(C++29 起) | |
选出 x 中 m 的为 1 的位,并将它们连续地压缩至右侧。剩余位为 0。
此重载仅当 T 为无符号整数类型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展无符号整数类型)时参与重载决议。
参数
| x | - | 无符号整数类型的值 |
| m | - | 无符号整数类型的值 |
返回值
x应用了通过掩码 m 进行位压缩后的 。
注解
此函数与 PEXT x86_64 和 BEXT ARM 指令的结果相同。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_bitops |
202606L |
(C++29) | 位排列 |
可能的实现
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;
}
|
示例
运行此代码
#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() {}
参见
(C++29) |
使用掩码从操作数展开位(PDEP) (函数模板) |