Formatting Unions inside bitfields in C

Viewed 771

I have a particular problem in which I have a 16 bit structure. Inside the structure, after the member "x_pos", depending on some external flag, the next 5 bits represent something different.

If the external flag is set, they are rotation & scaling parameters (rotscale_param), else the upper two bits are horizontal and vertical flip bits.

I've tried to represent this structure using a union, but when I so sizeof(attribute), I'm expecting to see 2 bytes, but the result is 4 bytes.

My Code:

typedef unsigned short u16;

struct attribute {
    u16 x_pos : 9;
    union {
        u16 rotscale_param : 5;
        struct {
            u16 unused : 3;
            u16 hflip : 1;
            u16 vflip : 1;
            };
    };
    u16 size : 2;
};

If it helps, I'm trying to make C code for this structure:

OBJ Attribute 
  Bit   Expl.
  0-8   X-Coordinate           
  When Rotation/Scaling used:
    9-13  Rotation/Scaling Parameter Selection
  When Rotation/Scaling not used:
    9-11  Not used
    12    Horizontal Flip      
    13    Vertical Flip        
  14-15 OBJ Size

Source of above quote : http://problemkaputt.de/gbatek.htm#lcdobjoamattributes

Here is a potential solution:

typedef struct attr_flag_set {
    u16 x_pos : 9;
    u16 rotscale_param : 5;
    u16 size : 2;
};

typedef struct attr_flag_unset {
    u16 x_pos : 9;
    u16 unused : 3;
    u16 hflip : 1;
    u16 vflip : 1;
    u16 size : 2;
};

union attribute_1 {
    attr_flag_unset attr_unset;
    attr_flag_set attr_set;
};

I'm not sure if this is the ideal solution, however.

2 Answers
Related