位字段允许用户修改结构体中某个成员变量的特定位数,这种实现对于一般的程序似乎没有什么价值,但是对于硬件工程师来说,可以创建与特定硬件设备上的寄存器对应的数据结构。
同时,如果空间宝贵,数据类型存储数据有空间冗余,也可以使用位字段优化。
比如,C++中,bool
类型仅存储0或1,但是与char
类型一样占1个字节,浪费空间。考虑到操作系统自动对齐,如果使用位字段,相同的空间可以存储8个bool
变量。
#include <iostream>
#include <string>
using namespace std;
struct withoutbits {
bool a;
};
struct withbits {
bool b : 1;
bool c : 1;
bool d : 1;
bool e : 1;
bool f : 1;
bool g : 1;
bool h : 1;
bool i : 1;
};
int main() {
cout << sizeof(withoutbits) << endl;
cout << sizeof(withbits) << endl;
return 0;
}
输出结果: