49. Control Register Using Nested Bitfields

#include <stdio.h>

typedef union {
    unsigned char reg;
    struct {
        unsigned char enable : 1;
        unsigned char mode : 1;
        unsigned char priority : 2;
        unsigned char reserved : 4;
    } bits;
} ControlRegister;

int validate_register(ControlRegister *ctrl) {
    if ((*ctrl).bits.enable != 1)
        return 0;

    if ((*ctrl).bits.priority > 2)
        return 0;

    if ((*ctrl).bits.reserved != 0)
        return 0;

    return 1;
}

int main() {
    ControlRegister ctrl;
    scanf("%hhx", &ctrl.reg);

    int result = validate_register(&ctrl);
    printf("%d", result);

    return 0;
}

Bitfields allow you to map hardware register layouts to individual fields cleanly.

Using a union lets you both access the entire register (reg) and its bitwise parts (bits) — common in peripheral access.

Solution Logic:

  • Check if enable bit is set to 1
  • Check if priority field is ≤ 2 (0–2 valid)
  • Check if all reserved bits (bits 4–7) are 0
  • Use pointer access (-> or (*p).) to validate each field

Alternate Solution

int validate_register(ControlRegister *ctrl) {
    return (ctrl->bits.enable == 1 &&
            ctrl->bits.priority <= 2 &&
            ctrl->bits.reserved == 0);
}


 

Loading...

Input

05

Expected Output

1