C Programming Bit Fields

Last modified by Microchip on 2023/11/09 09:06

Information
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

Byte in Data Memory (RAM) graphic