场景:
1.位域作为一个控制空间大小的语法特性其实是有它自己的用武之地的,比如网络通讯的协议定制,使用位域为1来严格限制bool值为0,1等等.
2.它有一些细节需要注意,
第一: 位域的大小是值的类型的整数倍,不足整数倍的补全.如unsigned short的大小是16位,那么如果总值17位的话会自动补全到16*2=32位.
第二: 赋值当然需要位运算符或者不超过它的最大值的整数.
代码:
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef unsigned int Bit;
class NetData
{
public:
Bit type: 1;
Bit valid: 1;
Bit delay_second: 4;
Bit command: 4;
Bit finished: 1;
Bit error: 4;
unsigned char t: 2;
};
int main(int argc, char const *argv[])
{
cout << "NetData size:" << sizeof(NetData) << endl;
NetData nd;
nd.ty