Define union that can access bits, nibbles, bytes

前端 未结 2 1647
旧巷少年郎
旧巷少年郎 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:11

    you can use bitfields in a struct like the following:

    typedef union
    {
      struct
      {
        unsigned char bit0 : 1;
        unsigned char bit1 : 1;
        unsigned char bit2 : 1;
        unsigned char bit3 : 1;
        unsigned char bit4 : 1;
        unsigned char bit5 : 1;
        unsigned char bit6 : 1;
        unsigned char bit7 : 1;
      }bits;
      unsigned char byte;
    }byte;
    

    and then if you'll have byte b;, you can access each bit like that: b.bits.bit1

提交回复
热议问题