67. Control Register Using Nested Bitfields

Back To All Submissions
Previous Submission
Next Submission

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 -> reg) & 0x01) == 1) &&
        ((((ctrl -> reg) >> 2) & 0x03) <= 2) &&
        ((((ctrl -> reg) >> 4) & 0xF) == 0)
        ) {
            return 1;
        }
        */
    if (ctrl -> bits.enable == 0) {
        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

 

 

 

Was this helpful?
Upvote
Downvote