Getting the size of an indiviual field from a c++ struct field(从 C++ struct 字段获取单个字段的大小)
问题描述
简短版本是:我如何了解 c++ 字段的单个字段的大小(以位为单位)?
The short version is: How do I learn the size (in bits) of an individual field of a c++ field?
为了澄清,我正在谈论的领域的一个例子:
To clarify, an example of the field I am talking about:
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.
获取整个Test对象的大小很简单,我们就说
To get the size of the entire Test object is easy, we just say
sizeof(Test); // returns 8, for 8 bytes total size
我们可以通过获取一个普通的struct成员
We can get a normal struct member through
sizeof(((Test*)0)->normal_member); // returns 4 (on my system)
我想知道如何获取单个字段的大小,例如 Test::field4.普通结构成员的上述示例不起作用.有任何想法吗?或者有人知道它不能工作的原因吗?我相当相信 sizeof 不会有帮助,因为它只以字节为单位返回大小,但如果有人知道否则我会全神贯注.
I would like to know how to get the size of an individual field, say Test::field4. The above example for a normal struct member does not work. Any ideas? Or does someone know a reason why it cannot work? I am fairly convinced that sizeof will not be of help since it only returns size in bytes, but if anyone knows otherwise I'm all ears.
谢谢!
推荐答案
可以在运行时计算大小,fwiw,例如:
You can calculate the size at run time, fwiw, e.g.:
//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 ...
这篇关于从 C++ struct 字段获取单个字段的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ struct 字段获取单个字段的大小
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01