C++ STL位集是否支持值字段?
目前,我使用位字段来表示c++中的标志寄存器:C++ STL位集是否支持值字段?,c++,stl,bit-manipulation,C++,Stl,Bit Manipulation,目前,我使用位字段来表示c++中的标志寄存器: struct DEVICE_REGISTER { unsigned ready:1; // 1 if device is ready unsigned error:1; // 1 if an error occurred. unsigned bus_address:4; // up to 16 possible drives on bus unsigned command:2;
struct DEVICE_REGISTER {
unsigned ready:1; // 1 if device is ready
unsigned error:1; // 1 if an error occurred.
unsigned bus_address:4; // up to 16 possible drives on bus
unsigned command:2; // up to 4 different commands
unsigned error_code:8;
};
执行按位操作干净、简单且直观:
{
dev_reg->bus_address = 1;
dev_reg->command = CmdReset;
/* wait until operation done, ready will be true */
while ( ! dev_reg->ready ) ;
/* check for errors */
if (dev_reg->error)
{ /* interrogate disk_reg->error_code for error type */
switch (dev_reg->error_code)
......
}
}
然而,为了提高效率,我想使用STL的位集
,但我不知道如何将一段位声明为名称引用的数据字段。以下显然不起作用:
struct DEVICE_REGISTER {
bitset<1> ready; // 1 if device is ready
bitset<1> error; // 1 if an error occurred.
bitset<4> bus_address; // up to 16 possible drives on bus
bitset<2> command; // up to 4 different commands
bitset<8> error_code;
};
if (dev_reg->error_code)
dev_reg->error_code = 0; // clear the error codes
dev_reg->error = 0;
resend(dev_reg); // resend the register
};
struct DEVICE\u寄存器{
位集就绪;//如果设备就绪,则为1
位集错误;//如果发生错误,则为1。
bitset bus_address;//总线上最多16个可能的驱动器
bitset命令;//最多4个不同的命令
位集错误代码;
};
如果(开发注册->错误代码)
dev_reg->error_code=0;//清除错误代码
dev_reg->error=0;
重新发送(dev_reg);//重新发送注册表
};
如果
bitset
不支持此功能,那么我很难看到使用它的任何真正好处。拥有更紧凑的数据结构所获得的好处,在代码量、复杂性、可读性和可靠性方面都有所损失。按值的位置和大小而不是按命名字段引用值容易出现人为错误,需要大量的代码练习。std::bitset不是位字段。它抽象了位访问,仅此而已。C位字段是一个很好的功能,只要您不想在不同的实现中对位字段的大小、对齐或填充有任何保证。bitset
甚至不能远程替代位字段。这两个人除了名字中的“比特”一词外没有任何共同之处。作为一个演示,检查两个定义中的sizeof(DEVICE\u REGISTER)
,这可能很有启发性。那么这都是一个大骗局?对MCU程序员来说没什么新鲜事?我是否可以至少将一个位字段转换为类似位集(dev_reg)的位集,并使用它来序列化IO的位?也许,它将正确地打包这些位。