Error trying to define a 1,024-bit (128 Byte) Bit Field

前端 未结 4 1786
走了就别回头了
走了就别回头了 2021-01-06 10:32

I would like to define a large bitfield for the purpose of quickly monitoring the status a very large structure of elements. Here is what I have so far:

#define T         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 10:43

    As other have said, the C standard doesn't allow bit-fields to exceed the size of their attached integer type.

    I'd suggest using plain arrays with some macro magic:

    #include 
    #include 
    #include 
    
    // SIZE should be a constant expression
    // this avoids VLAs and problems resulting from being evaluated twice
    #define BITFIELD(SIZE, NAME) \
        unsigned char NAME[(SIZE) / CHAR_BIT + ((SIZE) % CHAR_BIT != 0)]
    
    static inline void setbit(unsigned char field[], size_t idx)
    { field[idx / CHAR_BIT] |= 1u << (idx % CHAR_BIT); }
    
    static inline void unsetbit(unsigned char field[], size_t idx)
    { field[idx / CHAR_BIT] &= ~(1u << (idx % CHAR_BIT)); }
    
    static inline void togglebit(unsigned char field[], size_t idx)
    { field[idx / CHAR_BIT] ^= 1u << (idx % CHAR_BIT); }
    
    static inline _Bool isbitset(unsigned char field[], size_t idx)
    { return field[idx / CHAR_BIT] & (1u << (idx % CHAR_BIT)); }
    
    int main(void)
    {
        BITFIELD(1025, foo);
        printf("sizeof foo = %u\n", sizeof foo);
    
        memset(foo, 0, sizeof foo);
        printf("%i", isbitset(foo, 1011));
    
        setbit(foo, 1011);
        printf("%i", isbitset(foo, 1011));
    
        unsetbit(foo, 1011);
        printf("%i", isbitset(foo, 1011));
    }
    

    Hopefully, I didn't mess up the bit ops...

提交回复
热议问题