std::bit_repeat
From cppreference.com
| Defined in header <bit>
|
||
template< class T >
constexpr T bit_repeat( T pattern, int length );
|
(since C++29) | |
Repeats the bit pattern in pattern of length length as many times as fits into the result (with the last repetition potentially truncated).
If length is less than or equal to 0, the behavior is undefined. Call to this function is permitted in constant evaluation only if the undefined behavior does not occur.
Parameters
| pattern | - | the bit pattern to repeat |
| length | - | the length of the bit pattern |
| 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
The repeated bit pattern.
Exceptions
Throws nothing.
Notes
| 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_repeat(T pattern, int length) noexcept
{
T result = 0;
for (int i = 0; i != std::numeric_limits<T>::digits; ++i)
result |= ((pattern >> (i % length)) & 1) << i;
return result;
}
|
Example
Run this code
#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() {}
