Define union that can access bits, nibbles, bytes

前端 未结 2 1645
旧巷少年郎
旧巷少年郎 2021-01-15 03:52
union bits {
   unsigned int a : 1;
    unsigned int b : 2;
    unsigned int c : 3;
    unsigned int d : 4;``
    unsigned char x[2];
    unsigned int z; 
};
         


        
2条回答
  •  攒了一身酷
    2021-01-15 04:16

    You need a union of bitfields. If you just use a union all of your fields will point to the same place.

    union{
        struct {
            unsigned int bit1 : 1;
            unsigned int bit2 : 1;
            unsigned int bit3 : 1;
            unsigned int bit4 : 1;
            unsigned int bit5 : 1;
            unsigned int bit6 : 1;
            unsigned int bit7 : 1;
            unsigned int bit8 : 1;
            ...
            unsigned int bit32 : 1;
        };
        struct {
            unsigned int nibble1 : 4;
            unsigned int nibble2 : 4;
            ...
        };
        struct {
            unsigned int byte1 : 8;
            unsigned int byte2 : 8;
            ...
        };
        unsigned int int_value;
    }
    

提交回复
热议问题