What does 'unsigned temp:3' in a struct or union mean?

C++CBit FieldsColon

C++ Problem Overview


> Possible Duplicate:
> What does this C++ code mean?

I'm trying to map a C structure to Java using JNA. I came across something that I've never seen.

The struct definition is as follows:

struct op 
{
    unsigned op_type:9;  //---> what does this mean? 
    unsigned op_opt:1; 
    unsigned op_latefree:1; 
    unsigned op_latefreed:1; 
    unsigned op_attached:1; 
    unsigned op_spare:3; 
    U8 op_flags; 
    U8 op_private;
};

You can see some variable being defined like unsigned op_attached:1 and I'm unsure what would that mean. Would that effect the number of bytes to be allocated for this particular variable?

C++ Solutions


Solution 1 - C++

This construct specifies the length in bits for each field.

The advantage of this is that you can control the sizeof(op), if you're careful. the size of the structure will be the sum of the sizes of the fields inside.

In your case, size of op is 32 bits (that is, sizeof(op) is 4).

The size always gets rounded up to the next multiple of 8 for every group of unsigned xxx:yy; construct.

That means:

struct A
{
    unsigned a: 4;    //  4 bits
    unsigned b: 4;    // +4 bits, same group, (4+4 is rounded to 8 bits)
    unsigned char c;  // +8 bits
};
//                    sizeof(A) = 2 (16 bits)

struct B
{
    unsigned a: 4;    //  4 bits
    unsigned b: 1;    // +1 bit, same group, (4+1 is rounded to 8 bits)
    unsigned char c;  // +8 bits
    unsigned d: 7;    // + 7 bits
};
//                    sizeof(B) = 3 (4+1 rounded to 8 + 8 + 7 = 23, rounded to 24)

I'm not sure I remember this correctly, but I think I got it right.

Solution 2 - C++

It declares a bit field; the number after the colon gives the length of the field in bits (i.e., how many bits are used to represent it).

Solution 3 - C++

unsigned op_type:9;

Means op_type is an integer variable with 9 bits.

Solution 4 - C++

The colon modifier on integral types specifies how many bits the int should take up.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMunir AhmedView Question on Stackoverflow
Solution 1 - C++utnapistimView Answer on Stackoverflow
Solution 2 - C++James McNellisView Answer on Stackoverflow
Solution 3 - C++goedsonView Answer on Stackoverflow
Solution 4 - C++plinthView Answer on Stackoverflow