Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the size of an indiviual field from a c++ struct field

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.

To get the size of the entire Test object is easy, we just say

sizeof(Test); // returns 8, for 8 bytes total size

We can get a normal struct member through

sizeof(((Test*)0)->normal_member); // returns 4 (on my system)

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!

like image 318
Jeffrey Martinez Avatar asked Nov 29 '22 07:11

Jeffrey Martinez


1 Answers

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 ...
like image 85
ChrisW Avatar answered Dec 20 '22 04:12

ChrisW