位域写入大小
在 C++ 中,可以使用位域来定义一个结构体的成员变量占用的位数。但是,如果在写入位域变量时指定的字节数大于其实际占用的位数,就会出现'Bitfield write size”警告。例如:
struct MyStruct {
unsigned int a : 4;
unsigned int b : 5;
};
int main() {
MyStruct s;
s.a = 7;
s.b = 34; // 警告:Bitfield write size (5 bits) exceeds size of bit field (4 bits)
return 0;
}
要解决这个警告,需要在写入位域变量时保证指定的字节数正确。修改为:
struct MyStruct {
unsigned int a : 4;
unsigned int b : 5;
};
int main() {
MyStruct s;
s.a = 7;
s.b = 6;
return 0;
}
值得注意的是,位域类型是相对于 unsigned int 的,所以在写入位域变量时要保证指定的字节数不超过对应的 unsigned int 的字节数。