Define union that can access bits, nibbles, bytes

最后都变了- 提交于 2019-12-30 11:10:53

问题


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; 
};

Suppose in a union of 32 bits, i need to use a single bit, or a group of bits, or nibble, or bytes. is there a way to define the union.


回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/20005349/define-union-that-can-access-bits-nibbles-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!