How to get array of bits in a structure?

前端 未结 6 2209
走了就别回头了
走了就别回头了 2020-12-14 01:00

I was pondering (and therefore am looking for a way to learn this, and not a better solution) if it is possible to get an array of bits in a structure.

6条回答
  •  一个人的身影
    2020-12-14 01:44

    NOT POSSIBLE - A construct like that IS NOT possible(here) - NOT POSSIBLE

    One could try to do this, but the result will be that one bit is stored in one byte

    #include 
    #include 
    using namespace std;
    
    #pragma pack(push, 1)
    struct Bit
    {
        //one bit is stored in one BYTE
        uint8_t a_:1;
    };
    #pragma pack(pop, 1)
    typedef Bit bit;
    
    struct B
    {
        bit bits[4];
    };
    
    int main()
    {
        struct B b = {{0, 0, 1, 1}};
        for (int i = 0; i < 4; ++i)
            cout << b.bits[i] <

    output:

    0 //bit[0] value
    0 //bit[1] value
    1 //bit[2] value
    1 //bit[3] value
    1 //sizeof(Bit), **one bit is stored in one byte!!!**
    4 //sizeof(B), ** 4 bytes, each bit is stored in one BYTE**
    

    In order to access individual bits from a byte here is an example (Please note that the layout of the bitfields is implementation dependent)

    #include 
    #include 
    using namespace std;
    
    #pragma pack(push, 1)
    struct Byte
    {
        Byte(uint8_t value):
            _value(value)
        {
        }
        union
        {
        uint8_t _value;
        struct {
            uint8_t _bit0:1;
            uint8_t _bit1:1;
            uint8_t _bit2:1;
            uint8_t _bit3:1;
            uint8_t _bit4:1;
            uint8_t _bit5:1;
            uint8_t _bit6:1;
            uint8_t _bit7:1;
            };
        };
    };
    #pragma pack(pop, 1)
    
    int main()
    {
        Byte myByte(8);
        cout << "Bit 0: " << (int)myByte._bit0 <

提交回复
热议问题