正如其他人所说,C 标准不允许位域超过其附加整数类型的大小。
我建议使用带有一些宏魔法的普通数组:
#include <limits.h>
#include <stdio.h>
#include <string.h>
// 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));
}
希望我没有搞砸位操作...