3.3.4.2 How Can I Access Individual Bits of a Variable?
There are several ways of doing this. The simplest and most portable way is to define an integer variable and use macros to read, set, or clear the bits within the variable using a mask value and logical operations, such as the following.
#define testbit(var, bit) (!!(var) & (1 <<(bit)))
#define setbit(var, bit) ((var) |= (1 << (bit)))
#define clrbit(var, bit) ((var) &= ~(1 << (bit)))
These, respectively, test to see if bit number, bit
, in
the integer, var
, is set; set the corresponding bit
in
var
; and clear the corresponding bit
in
var
. Alternatively, a union of an integer variable and a structure with
bit-fields (see 9.5.2 Bit Fields in Structures) can
be defined, for example,
union both {
unsigned char byte;
struct {
unsigned b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1;
} bitv;
} var;
This allows you to access byte
as a whole (using
var.byte), or any bit within that variable independently (using
var.bitv.b0
through var.bitv.b7
).