63. Register Bitfields Using Struct Overlay

#include <stdio.h>
#include <stdint.h>

typedef union {
    struct {
        uint8_t enable    : 1;
        uint8_t mode      : 2;
        uint8_t interrupt : 1;
        uint8_t reserved  : 4;
    } bits;
    uint8_t reg;
} ControlRegister;

int main() {
    uint8_t e, m, i;
    scanf("%hhu %hhu %hhu", &e, &m, &i);

    ControlRegister ctrl = {0};
    ctrl.bits.enable = e;
    ctrl.bits.mode = m;
    ctrl.bits.interrupt = i;

    printf("%u", ctrl.reg);
    return 0;
}

What is this about?

This demonstrates how to use bitfield structs to model register layouts in C, letting you read/write individual bits with intuitive field names instead of manual masking.

Why it’s important in firmware?

  • Matches hardware register layout
  • Reduces code complexity
  • Makes code more readable and maintainable

Solution Logic

  • Overlay a struct and raw uint8_t using union
  • Assign to individual fields
  • Print the register as a complete byte

 

Loading...

Input

1 2 1

Expected Output

13