Control Register Using Nested Bitfields

Code

#include <stdio.h>
#include <stdbool.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) {
    bool enT= (ctrl->bits.enable==1)?1:0;
  // bool modeT= (ctrl->bits.mode==1)?1:0;
    bool priorityT= (ctrl->bits.priority<=2)?1:0;
    bool resT= (ctrl->bits.reserved==0)?1:0;  


    return (enT&& priorityT&& resT);
}

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

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

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

05

Expected Output

1