C Programming Bit Fields
Last modified by Microchip on 2023/11/09 09:06
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
}
{
unsigned int memberName1: bitWidth;
…
unsigned int memberNamen:bitWidth
}
Example
1
2
3
4
5
6
7
8
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;
{
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