Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 259
Munir Ahmed Avatar asked Jun 01 '10 13:06

Munir Ahmed


2 Answers

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.

like image 60
utnapistim Avatar answered Nov 18 '22 05:11

utnapistim


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).

like image 20
James McNellis Avatar answered Nov 18 '22 04:11

James McNellis