Search code examples
cstructtypedefbit-fieldsunions

How to initialize an int buried 2 levels deep inside typdef'd unions


I would like to perform the following

static Type2 MyData;
MyData.Base.Data = (0b0000000000010100);

as a static initialization. For example

static Type2 MyData = (typecast)(0b0000000000010100);

What would I typecast this with? Here are the typedefs for Type1 and Type2

typedef union
{
    UINT16 Data;
    struct
    {
        unsigned      :10;  
        unsigned var1 :3;   
        unsigned var2 :2;   
        unsigned var3 :1;   
    };
} Type1;    

typedef union
{
    Type1 Base;     
    struct
    {
        unsigned var4 :3;
        unsigned var5 :2;   
        unsigned      :11;
    } Data;
} Type2;

Solution

  • Similar to this question, try Type2 t = { .Base.Data = 0x18 }; If your goal is to set the bitfields in Type1 you should probably call them out directly; see here.