0
0
Embedded Cprogramming~5 mins

Bit field structures in Embedded C

Choose your learning style9 modes available
Introduction

Bit field structures let you store many small pieces of information in a single variable. This saves memory by using only the needed bits.

When you want to save memory in small devices like microcontrollers.
When you need to represent flags or options that are either on or off.
When you want to work with hardware registers that use specific bits for settings.
When you want to pack multiple small values tightly in one variable.
Syntax
Embedded C
struct Name {
    unsigned int field1 : number_of_bits;
    unsigned int field2 : number_of_bits;
    // ...
};
Each field after the colon (:) specifies how many bits it uses.
Fields must be of type unsigned int or int.
Examples
This structure has three fields using 1, 2, and 1 bits respectively.
Embedded C
struct Flags {
    unsigned int is_on : 1;
    unsigned int mode : 2;
    unsigned int error : 1;
};
Here, count uses 4 bits, enough to store values 0-15.
Embedded C
struct Status {
    unsigned int ready : 1;
    unsigned int count : 4;
    unsigned int reserved : 3;
};
Sample Program

This program creates a bit field structure to store device status flags. It sets and prints each field.

Embedded C
#include <stdio.h>

struct DeviceStatus {
    unsigned int power_on : 1;
    unsigned int error_code : 3;
    unsigned int mode : 2;
};

int main() {
    struct DeviceStatus status = {0};

    status.power_on = 1;    // Turn device on
    status.error_code = 5;  // Set error code (max 7)
    status.mode = 2;        // Set mode (max 3)

    printf("Power On: %u\n", status.power_on);
    printf("Error Code: %u\n", status.error_code);
    printf("Mode: %u\n", status.mode);

    return 0;
}
OutputSuccess
Important Notes

Bit fields help save memory but may be slower to access than normal variables.

Bit field sizes must fit within the type size (usually 32 bits for unsigned int).

Be careful with portability: bit field order and packing can vary by compiler.

Summary

Bit field structures store small pieces of data using specific bits.

They save memory and are useful for flags and hardware control.

Use the colon syntax to set how many bits each field uses.