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

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.

Leave a Comment