Jef*_*nez 3 c++ struct field sizeof
简短版本是:如何学习c ++字段的单个字段的大小(以位为单位)?
澄清一下,我所谈论的领域的一个例子:
struct Test {
unsigned field1 : 4; // takes up 4 bits
unsigned field2 : 8; // 8 bits
unsigned field3 : 1; // 1 bit
unsigned field4 : 3; // 3 bits
unsigned field5 : 16; // 16 more to make it a 32 bit struct
int normal_member; // normal struct variable member, 4 bytes on my system
};
Test t;
t.field1 = 1;
t.field2 = 5;
// etc.
Run Code Online (Sandbox Code Playgroud)
我们只是说,要获得整个Test对象的大小很简单
sizeof(Test); // returns 8, for 8 bytes total size
Run Code Online (Sandbox Code Playgroud)
我们可以得到一个普通的struct成员
sizeof(((Test*)0)->normal_member); // returns 4 (on my system)
Run Code Online (Sandbox Code Playgroud)
我想知道如何获得单个字段的大小,比如Test :: field4.上面的普通struct成员示例不起作用.有任何想法吗?或者有人知道它无法工作的原因吗?我相信sizeof不会有任何帮助,因为它只返回大小的字节数,但如果有人知道,我会全神贯注.
谢谢!
Chr*_*isW 10
您可以在运行时计算大小,fwiw,例如:
//instantiate
Test t;
//fill all bits in the field
t.field1 = ~0;
//extract to unsigned integer
unsigned int i = t.field1;
... TODO use contents of i to calculate the bit-width of the field ...
Run Code Online (Sandbox Code Playgroud)
你不能取sizeof一个位域并获得位数.
你最好的选择是使用#defines或enums:
struct Test {
enum Sizes {
sizeof_field1 = 4,
sizeof_field2 = 8,
sizeof_field3 = 1,
sizeof_field4 = 3,
sizeof_field5 = 16,
};
unsigned field1 : sizeof_field1; // takes up 4 bits
unsigned field2 : sizeof_field2; // 8 bits
unsigned field3 : sizeof_field3; // 1 bit
unsigned field4 : sizeof_field4; // 3 bits
unsigned field5 : sizeof_field5; // 16 more to make it a 32 bit struct
int normal_member; // normal struct variable member, 4 bytes on my system
};
printf("%d\n", Test::sizeof_field1); // prints 4
Run Code Online (Sandbox Code Playgroud)
为了统一起见,我相信你可以移动normal_member到顶部,并添加一个条目Sizes使用sizeof(normal_member).但这会与您的数据顺序混淆.
| 归档时间: |
|
| 查看次数: |
8298 次 |
| 最近记录: |