Namespaces
Variants

std::bit_repeat

来自 zh.cppreference.net
 
 
 
位操作
(C++20)
(C++23)
2的整数次幂2
(C++20)
(C++20)
(C++20)
移位
(C++29)
(C++29)
旋转
(C++20)
(C++20)
计数
(C++20)
(C++20)
(C++20)
排列
(C++29)
(C++29)
字节序
(C++20)
 
定义于头文件<bit>
template< class T >
constexpr T bit_repeat( T x, int l );
(自C++29起)

重复x中的位模式l次,直到填满结果(最后一次重复可能被截断)。

如果l小于或等于0,则行为未定义。只有在未定义行为不会发生时,才允许在常量求值中调用此函数。

只有当T是无符号整数类型(即unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long或扩展无符号整数类型)时,此重载才会参与重载解析。

参数

x - 无符号整数类型的值

返回值

重复的位模式。

异常

不抛出任何异常。

注解

特性测试 宏 值 标准 功能
__cpp_lib_bitops 202606L (C++29) 位排列

可能的实现

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

// This is a valid, but highly inefficient version of bit_repeat.
template<std::unsigned_integral T>
    requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr T bit_repeat_naive(T x, int l) noexcept
{
    T result = 0;
    for (int i = 0; i != std::numeric_limits<T>::digits; ++i)
        result |= ((x >> (i % length)) & 1) << i;
    return result;
}

// Constant-time implementation (preferred).
template<std::unsigned_integral T>
    requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr T bit_repeat(T x, int l) noexcept
{
    static constexpr auto lookup = []
    {
        std::array<T, std::numeric_limits<T>::digits> result{};
        for (std::size_t i = 1; i != result.size(); ++i)
            result[i] = bit_repeat_naive(one, l);
        return result;
    }();
    if (l >= std::numeric_limits<T>::digits)
        return x;
    T mask = (T{1} << l) - T{1};
    return lookup[l] * (mask & x);
}

示例

#include <bit>
#include <cstdint>

static_assert(
    std::bit_repeat(
        std::uint8_t{1}, 1) ==
        std::uint8_t{0b1111'1111} and
    std::bit_repeat(
        std::uint8_t{0b1110}, 2) ==
        std::uint8_t{0b1010'1010} and
    std::bit_repeat(
        std::uint8_t{0b101}, 3) ==
        std::uint8_t{0b1'101'101} and
    std::bit_repeat(
        std::uint16_t{0b1100}, 4) ==
        std::uint16_t{0b1100'1100'1100'1100}
);

int main() {}

参阅

反转整数中的位
(函数模板)
使用掩码压缩操作数的位(PEXT)
(函数模板)
使用掩码扩展操作数的位(PDEP)
(函数模板)