![]() |
![]() |
TOP > C++ > ビットフィールド |
![]() |
![]() |
ビットフィールドとは?
構造体のメンバのビットを指定ビットにすることができる。例えば、2bitと4bitの2つの変数がほしい。このような時に使用する。ビットフィールドが使用できる型は、signed int, unsigned intの2つである。
構造体のサイズは必ずintの倍数に揃えられる。まずは簡単な例を紹介します。
ビットフィールドの例1
#include <iostream> using namespace std; struct { unsigned int a : 2; unsigned int b : 1; }bittest_1; int main(int argc, char** argv) { cout << "構造体のサイズは、" << sizeof(bittest_1) << "です" << endl; cout << "また、intのサイズは、" << sizeof(int) << "です" << endl; return 0; } 上記の結果で表示されるバイト数は、intサイズと一緒になります。構造体のメンバに2つのint型のメンバーがありますが、ビットフィールドを指定した事によりbitの合計がintのサイズに収まるバイト数となります。
例えば、上記の例のメンバ一個を32bitに変更すると2つのbit合計は33bit以上となり、intでは収まらないので8byteのサイズとなります。
ビットフィールドの注意点
1.ビットフィールドの最大値はint型となるので、2つのメンバのbit値がint型のサイズより大きい場合は結合されません。
ビットフィールドのサイズの例
#include <iostream> using namespace std; struct { unsigned int a : 28; unsigned int b : 10; unsigned int c : 24; }bittest_2; int main(int argc, char** argv) { cout << "構造体のサイズは、" << sizeof(bittest_2) << "です" << endl; return 0; } 上記の結果で構造体のサイズはintの3倍のサイズとなります。メンバaとメンバbのbit合計は38bitとなり、intのサイズを超えています。この場合各々が32bitに割り当てられます。
次のメンバbとメンバcの合計も範囲外なので、結果として全てのメンバが独立してintのサイズ分割り当てられます
2.空bitを置くことができます。空bitを置くには、変数名を記入しないだけです。
空bitの例
struct { unsigned int a : 3; unsigned int : 4; unsigned int b : 1; }bittest_3; 3.強制的に次のintサイズへ割り当てる事もできます。この場合は、名前無しの変数のbit値を0にします。
次のサイズに割り当てる例
struct { unsigned int a : 3; unsigned int : 0; unsigned int b : 1; }bittest_4; 実際の使用方法
ビットフィールドは共用体と一緒に使用する事が多いと思います。「あるbitの変数を連結して表示する」とかに使用します。例を示します。この例では32bitの変数を4bit毎に分割して各々に値を格納し、連結した値を出力してみます。
ビットフィールドと共用体の例
#include <iostream> using namespace std; union { struct { unsigned int a : 4; unsigned int b : 4; unsigned int c : 4; unsigned int d : 4; unsigned int e : 4; unsigned int f : 4; unsigned int g : 4; unsigned int h : 4; }bittest; unsigned int data; }test_1; union { struct { unsigned int a : 1; unsigned int b : 1; unsigned int c : 1; unsigned int d : 1; unsigned int e : 1; unsigned int f : 1; unsigned int g : 1; unsigned int h : 1; }bittest; unsigned char data; }test_2; int main(int argc, char** argv) { test_1.bittest.a = 15; test_1.bittest.b = 15; test_1.bittest.c = 15; test_1.bittest.d = 15; test_1.bittest.e = 15; test_1.bittest.f = 15; test_1.bittest.g = 15; test_1.bittest.h = 15; cout << "test_1.data = " << test_1.data << endl; test_2.data = 255; cout << "test_2.bittest.a = " << test_2.bittest.a << endl; cout << "test_2.bittest.b = " << test_2.bittest.b << endl; cout << "test_2.bittest.c = " << test_2.bittest.c << endl; cout << "test_2.bittest.d = " << test_2.bittest.d << endl; cout << "test_2.bittest.e = " << test_2.bittest.e << endl; cout << "test_2.bittest.f = " << test_2.bittest.f << endl; cout << "test_2.bittest.g = " << test_2.bittest.g << endl; cout << "test_2.bittest.h = " << test_2.bittest.h << endl; return 0; } |
![]() |
![]() |
Copyright 2007 ためになるホームページ All Rights Reserved. |