在C中用单位测试和设置单个位的经典问题可能是最常见的中级编程技能之一.您可以使用简单的位掩码进行设置和测试
unsigned int mask = 1<<11;
if (value & mask) {....} // Test for the bit
value |= mask; // set the bit
value &= ~mask; // clear the bit
Run Code Online (Sandbox Code Playgroud)
一篇有趣的博客文章认为,这容易出错,难以维护,而且做法不佳.C语言本身提供了类型安全和可移植的位级访问:
typedef unsigned int boolean_t;
#define FALSE 0
#define TRUE !FALSE
typedef union {
struct {
boolean_t user:1;
boolean_t zero:1;
boolean_t force:1;
int :28; /* unused */
boolean_t compat:1; /* bit 31 */
};
int raw;
} flags_t;
int
create_object(flags_t flags)
{
boolean_t is_compat = flags.compat;
if (is_compat) …Run Code Online (Sandbox Code Playgroud) 我有一个代码,它使用如下声明的位字段
typedef struct my{
const char *name;
uint8_t is_alpha : 1;
uint8_t is_hwaccel : 1;
uint8_t x_chroma_shift;
uint8_t y_chroma_shift;
} mystr;
Run Code Online (Sandbox Code Playgroud)
uint8_t是typedef'ed unsigned char.
使用此位字段在MS-VS 2008中构建代码会发出如下警告:
imgconvert.c(60) : warning C4214: nonstandard extension used : bit-field types other than int.