最終更新日時:
が更新

履歴 編集

function template
<bit>

std::bit_compress(C++29)

namespace std {
  template <class T>
  constexpr T bit_compress(T x, T m) noexcept; // C++29
}

概要

マスクmでビットが立っている位置のxのビットを集め、結果の下位ビットへ詰めて配置する(parallel bits extract)。

x86のPEXT命令に相当する操作である。

テンプレートパラメータ制約

  • Tが符号なし整数型であること

戻り値

Tのビット数をNとする。mの第nビットが1である位置を下位から順に走査し、対応するxの第nビットを結果の下位側から順に詰めた値を返す。すなわち、結果の第kビットは、mのなかでk番目に立っているビット位置のxのビットに等しい。

例外

投げない

備考

  • bit_expandは逆操作である。mのビットがすべて1のとき、bit_expand(bit_compress(x, m), m)xに等しい。

#include <bit>
#include <cstdint>
#include <print>

int main()
{
  std::uint8_t x = 0b1011'0100;
  std::uint8_t m = 0b1111'0000; // 上位4ビットを抽出

  std::uint8_t r = std::bit_compress(x, m);

  std::println("{:08b}", r);
}

出力

00001011

バージョン

言語

  • C++29

処理系

関連項目

参照