Search code examples
c++cbit-fields

VStudio c++ alignment of bitfield in union


In VStudio 2010, I'm trying to create a union to access a 2-byte value conveniently:

#pragma pack(push,1) // disable padding
typedef struct {
    uint8_t r:3;
    uint8_t g:3;
    uint8_t b:3;
}tsRgb;

typedef union {
    uint16_t raw;
    tsRgb rgb; 
}tPixelData;
#pragma pack(pop)

int main(){
    tPixelData pixel;
    pixel.raw = 0xABE5;
    return 0;
}

I'm expecting to see pixel.r = 5, pixel.g = 4, pixel.b = 7. the r and g are ok, but the b is 3.

What am I doing wrong? I assume I'm not alligning the bits correctly?


Solution

  • The third field will be in a separate byte.

    In VC++ the bitfields do not cross the boundaries of the underlying type. When you have used 3+3 bits there are only 2 left, so the next field will use 3 bits from a fresh byte.

    It might work better if you use uint16_t instead of uint8_t.

    "Disable padding" works on the byte level, not on the bit level.