views:

236

answers:

4

Hi,

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 follow,

struct op 
{
    unsigned op_type:9;  //---> what does this means? 
    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 number of bytes to be allocated for this particular variable?

any help?

Thanks,

Munir

+11  A: 

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

James McNellis
+2  A: 

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

plinth
+1  A: 
unsigned op_type:9;

Means op_type is an integer variable with 9 bits.

goedson
+4  A: 

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.

utnapistim
Remember kids! bit fields are compiler dependent, there is no C/C++ standard that specfies that the first 4 bits must be used on the a:4 above.
gbrandt