我之前有C语言的经验,但我从未接触过位域特性。我知道可以使用位掩码来隔离数据结构中的某些位,但是为什么还要使用位域呢?
例如,假设我们要隔离的位是最不显著的前3位。那么我们可以编写:
/* our bitmasks */
#define FIELD_A (1 << 0)
#define FIELD_B (1 << 1)
#define FIELD_C (1 << 2)
int main(void)
{
/* the data structure that contains our three fields */
uint8_t flags;
/* accessing field A (as a boolean) */
int bool_a = !!(flags & FIELD_A);
/* accessing field B (as a boolean) */
int bool_b = !!(flags & FIELD_B);
/* accessing field C (as a boolean) */
int bool_c = !!(flags & FIELD_C);
return 0;
}
为什么我们要把它写成这样:
?
static struct fields {
int field_a : 1;
int field_b : 1;
int field_c : 1;
};
int main(void)
{
/* the data structure that contains our three fields */
struct fields flags;
/* accessing field A */
int bit_a = flags.a;
/* accessing field B */
int bit_b = flags.b;
/* accessing field C */
int bit_c = flags.c;
return 0;
}
#define
中定义的数字,而不是FIELD_X
本身。 - Thomas Jagerint field_a : 1;
实际上是不正确的:一个只有一位的int
位域如果被设置可能会被读作-1
而非1
。你应该写成unsigned int field_a : 1;
。 - chqrlie