How to get array of bits in a structure?

前端 未结 6 2207
走了就别回头了
走了就别回头了 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:50

    this is abusive, and relies on an extension... but it worked for me:

    struct __attribute__ ((__packed__)) A
    {
        unsigned int bit0:1;
        unsigned int bit1:1;
        unsigned int bit2:1;
        unsigned int bit3:1;
    };
    union U
    {
        struct A structVal;
        int intVal;
    };
    
    int main()
    {
        struct A a = {1, 0, 1, 1};
        union U u;
        u.structVal = a;
        for (int i =0 ; i<4; i++)
        {
            int mask = 1 << i;
            printf("%d\n", (u.intVal &  mask) >> i);
        }
        return 0;
    }
    

提交回复
热议问题