Control Register Using Nested Bitfields

Code

#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;

// Write your logic here
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;
}

Solving Approach

  • Use a union so the same 8-bit value can be accessed:
    • as a raw byte (reg)
    • and as structured bitfields (bits)
  • Define bitfields inside a struct:
    • enable → 1 bit
    • mode → 1 bit
    • priority → 2 bits
    • reserved → 4 bits
  • Read the hex input into the union’s reg member.
    This automatically fills the bitfields because both share the same memory.
  • Validate the register:
    • enable must be 1
    • priority must be 0–2
    • reserved must be 0
  • If all checks pass → return 1, else return 0

 

 

Upvote
Downvote
Loading...

Input

05

Expected Output

1