从c ++ struct字段获取单个字段的大小 [英] Getting the size of an indiviual field from a c++ struct field

查看:162
本文介绍了从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

我们可以通过

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.

谢谢! >

Thanks!

推荐答案

您可以计算运行时的大小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字段获取单个字段的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆