gpt4 book ai didi

c++ - 如何处理位字段中的单位( bool )成员?

转载 作者:行者123 更新时间:2023-11-28 02:27:14 24 4
gpt4 key购买 nike

当我请求或设置按位的 struct/class 的一位成员时,编译器会进行位移吗?例如,给定此 struct:

struct {
unsigned char thing : 4;
unsigned char flag1 : 1;
unsigned char flag2 : 1;
unsigned char reserved : 2;
}

...编译器是否意识到不需要移位?换句话说,编译器是否这样做:

uchar request_flag1() const {
uchar temp = data & 0x40; //0100 0000 - get the 7th bit
return temp >> 7; //0000 0001 - return the shifted value
}
void set_flag1(uchar v) {
data &= 0x191; //1011 1111 - clear the 7th bit
data |= v << 7; //0v00 0000 - set the 7th bit to shifted value
}

还是这个?

bool request_flag1() const {
return data & 0x40; //0100 0000 - simply check whether the 7th bit is set
}
void set_flag1(bool v) {
if(v) data |= 0x40; //0100 0000 - simply set the 7th bit
else data &= 0x191; //1011 1111 - simply clear the 7th bit
}

我想后者会明显更快,因为它是操作数量的一半。

如果后者为真,我是否必须将位域成员声明为 bool 类型才能获得此优势?

最佳答案

编译器会将您的位操作转换为完成工作所需的任何系列的按位与/或/非操作。

例如

s.flag1 = 1;

会变成

s = s | 00000010;
^^^^^^-----stuff
^----flag1
^---flag2

实际分配的值将取决于您正在编译的特定 CPU 的位/字节顺序。

关于c++ - 如何处理位字段中的单位( bool )成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com