【C言語】stdbit.hを使って出来ることと典型的な使い方【標準ライブラリ】
stdbit.hとは
stdbit.h
は、C23 標準で導入されたヘッダーファイルで、ビット操作を簡単に行うための関数が提供されています。
これまではGCCのビルトイン関数や手書きのコードで対応していたビット操作を、統一的なインターフェースで扱えるようになりました。
主な機能には以下のようなものがあります:
- ビットカウント(ポピュレーションカウント)
- 最上位ビット・最下位ビットの検索
- ビットのローテーション
- ビットマスクの適用
ビットカウント(popcount)
popcount(ポピュレーションカウント)は、整数の中に含まれる「1」のビットの数を数える処理です。
#include <stdio.h>
#include <stdbit.h>
int main() {
unsigned int x = 0b101101; // 45
printf("1のビット数: %d\n", stdc_popcount(x));
return 0;
}
出力:
1のビット数: 4
最上位・最下位ビットの検索
最上位ビット(leading bit)や最下位ビット(trailing bit)の位置を取得できます。
#include <stdio.h>
#include <stdbit.h>
int main() {
unsigned int x = 0b100100; // 36
printf("最上位ビットの位置: %d\n", stdc_leading_zeros(x));
printf("最下位ビットの位置: %d\n", stdc_trailing_zeros(x));
return 0;
}
出力:
最上位ビットの位置: 26
最下位ビットの位置: 2
ビットのローテーション
ビットのローテーション(回転)は、ビット列を左右に回転させる操作です。
#include <stdio.h>
#include <stdbit.h>
int main() {
unsigned int x = 0b1101; // 13
printf("左ローテーション: %u\n", stdc_rotl(x, 2));
printf("右ローテーション: %u\n", stdc_rotr(x, 2));
return 0;
}
ビットマスクの操作
ビットマスクを使用すると、特定のビットを操作しやすくなります。
#include <stdio.h>
#include <stdbit.h>
int main() {
unsigned int x = 0b101010;
unsigned int mask = 0b111100;
printf("マスク適用: %u\n", x & mask);
return 0;
}
実践的な使用例
実際のプログラムでの利用例として、ビットカウントを使った高速なパリティチェックを示します。
#include <stdio.h>
#include <stdbit.h>
int check_parity(unsigned int x) {
return stdc_popcount(x) % 2;
}
int main() {
unsigned int x = 0b110101; // 53
printf("パリティ: %d\n", check_parity(x));
return 0;
}
まとめ
stdbit.h
を使用すると、従来GCCや手書きコードに依存していたビット操作を統一的な標準関数で簡潔に記述できます。