Bitfields in C for accessing microcontroller registers

These bitfields can be grouped to form a field of any size needed. Suppose a register field which selects an ADC channel is 3-bit wide then you can declare a field which is 3-bits in size and use it easily.

For example.,

If you want to declare a 8bit register with one-2bit bitfield, one-3bit bitfield, one-1bit bitfield, then the code will be,

// declaration

typedef union

{

    unsigned char Byte;

    struct

    {

         unsigned char bit012 : 3;

         unsigned char bit34 : 2;

         unsigned char bit5 : 1;

         unsigned char bit6 : 1;

         unsigned char bit7 : 1;

     }bits;

}registerType;

// define a pointer and cast it to point to the registers memory location

registerType *pReg = (registerType*)0x00008000;

// use the fields as

pReg->bits.bit5 = 1;

pReg->bits.bit012 = 7;

// access the whole byte as

pReg->Byte = 0x55;

The above example is for a little endian microcontroller, If your microcontroller is a big endian microcontroller then the higher bit fields should be declared first. However todays compilers are smart enough to take care of the endianness of the microcontroller.

Leave a Comment