Bit Fields
Bit fields are unsigned int members of structures that occupy a specified number of adjacent bits from one to sizeof(int). They may be used as an ordinary int variable in arithmetic and logical operations.
Bit fields are ordinary members of a structure and have a specific bit width. They are often used in conjunction with unions to provide bit access to a variable without masking operations.
Creating a Bit Field
Syntax
struct structName
{
unsigned int memberName1: bitWidth;
…
unsigned int memberNamen:bitWidth
}
Example
|
1
2
3
4
5
6
7
8
|
typedef struct{ unsigned int bit0: 1; unsigned int bit1to3: 3; unsigned int bit4: 1; unsigned int bit5: 1; unsigned int bit6to7: 2;} byteBits; |
A bit field struct may be declared normally or as a typedef
Using a Bit Field
Example
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
struct byteBits{ unsigned a: 1; unsigned b: 1; unsigned c: 2; unsigned d: 1; unsigned e: 3; } x;int main(void){ x.a = 1; //x.a may contain values from 0 to 1 x.b = 0; //x.b may contain values from 0 to 1 x.c = 0b10; //x.c may contain values from 0 to 3 x.d = 0x0; //x.d may contain values from 0 to 1 x.e = 7; //x.e may contain values from 0 to 7} |
