场景:
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
本文探讨了C/C++中不常见的位域语法特性,特别是在网络通讯协议定制中的应用。位域可以用于严格限制bool值为0或1。在使用位域时,应注意位域大小为值类型整数倍,不足时会自动补全。赋值通常需要借助位运算符或不超过最大值的整数。
订阅专栏 解锁全文
1485

被折叠的 条评论
为什么被折叠?



