【C++】 std::bitビット操作を効率的に行う【標準ライブラリ】

【C++】 std::bitビット操作を効率的に行う【標準ライブラリ】

標準ライブラリ<std::bit>で出来ることと典型的な使い方

標準ライブラリ<std::bit>で出来ることと典型的な使い方

std::bitとは

C++20 で追加された <bit> ヘッダには、ビット操作を効率的に行うための関数が含まれています。これにより、手動でビット演算を行うよりも簡潔で可読性の高いコードを書くことができます。

ビットカウント関連の関数

ビットの数を数えたり、最上位ビットの位置を取得するための関数が提供されています。

std::popcount

整数のビットが 1 である個数を返します。

#include <bit>
#include <iostream>

int main() {
    unsigned int x = 0b11011010; // 218
    std::cout << std::popcount(x) << std::endl; // 出力: 5
}

std::countl_zero / std::countl_one

最上位ビット(左側)から 0 または 1 の連続する数を取得します。

#include <bit>
#include <iostream>

int main() {
    unsigned int x = 0b00001111'00000000;
    std::cout << std::countl_zero(x) << std::endl; // 出力: 4
    std::cout << std::countl_one(x) << std::endl;  // 出力: 0
}

std::countr_zero / std::countr_one

最下位ビット(右側)から 0 または 1 の連続する数を取得します。

#include <bit>
#include <iostream>

int main() {
    unsigned int x = 0b00001111'00000000;
    std::cout << std::countr_zero(x) << std::endl; // 出力: 8
}

ビット操作関連の関数

特定のビット位置を取得したり、ビットの反転を行う関数があります。

std::bit_width

値を表現するのに必要な最小ビット数を取得します。

#include <bit>
#include <iostream>

int main() {
    unsigned int x = 37; // 0b100101
    std::cout << std::bit_width(x) << std::endl; // 出力: 6
}

std::rotl / std::rotr

ビットを左または右に回転させます。

#include <bit>
#include <iostream>

int main() {
    unsigned int x = 0b00001111;
    std::cout << std::bitset<8>(std::rotl(x, 2)) << std::endl; // 00111100
    std::cout << std::bitset<8>(std::rotr(x, 2)) << std::endl; // 11000011
}

エンディアン関連の関数

整数のバイト順序(エンディアン)を調べたり変換するための関数があります。

std::endian

エンディアンの判定を行います。

#include <bit>
#include <iostream>

int main() {
    if constexpr (std::endian::native == std::endian::little) {
        std::cout << "Little Endian" << std::endl;
    } else {
        std::cout << "Big Endian" << std::endl;
    }
}

std::byteswap

バイトオーダーを逆転させます(リトルエンディアン <-> ビッグエンディアン変換)。

#include <bit>
#include <iostream>

int main() {
    uint32_t x = 0x12345678;
    uint32_t y = std::byteswap(x);
    std::cout << std::hex << y << std::endl; // 出力: 0x78563412
}

最適化とユースケース

C++20 の <bit> は、従来の手動ビット演算よりも効率的で、安全にビット操作を行う手段を提供します。

ユースケース

  • ビットマスクを用いた高速データ処理
  • ハッシュ関数の最適化
  • エンディアン変換を使ったネットワーク通信
  • 固定長整数を用いた省メモリデータ構造

これらの機能を活用することで、パフォーマンスと可読性を両立したコードを書くことができます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です