Question

I have some issue with struct including bit fields. Consider the following code:

#pragma pack(push, 1)
struct DATA_WARNINGS {
    unsigned char fl_num        : 8;
    unsigned char dev_reload    : 1;
    unsigned char               : 1;
    unsigned long long flags    : 54;
};
#pragma pack(pop)

The size of such structure is 10 bytes as expected. What I would like to do is to fit this structure in 8 bytes without changing the width of the bit fields. So what I did is changed the type of the first field to unsigned long long. Like this:

#pragma pack(push, 1)
struct DATA_WARNINGS {
    unsigned long long fl_num   : 8;
    unsigned char dev_reload    : 1;
    unsigned char               : 1;
    unsigned long long flags    : 54;
};
#pragma pack(pop)

I expected that all structure fit in one unsigned long long. But actually size of such structure became 17 bytes returned by sizeof. If I change all fields type to unsigned long long than structure size becomes 8 bytes. The question is how to fit structure in 8 bytes without changing fields type to much. I'm using VS2013 on 32 bit machine.

Was it helpful?

Solution

Generally, when dealing with bit fields, the size/layout is entirely up to the compiler.

The reason for the odd structure sizes is in fact because the underlying type (unsigned long long vs unsigned char) is different, so the compiler won't try to merge the bit-fields. When they're all unsigned long long, the compiler can merge them into a single 8-byte quantity. Thus, there's really no workaround except to change everything to unsigned long long.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top