std::bit_repeat
ja.cppreference.net より
| ヘッダ <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() {}
関連項目
(C++29) |
整数のビットを反転します (関数テンプレート) |
(C++29) |
マスクを使用してオペランドのビットを圧縮します (PEXT) (関数テンプレート) |
(C++29) |
マスクを使用してオペランドからビットを展開します (PDEP) (関数テンプレート) |