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) >> 4))
    {
        if ((ctrl->reg) & 0x01)
        {
            if ((((ctrl->reg) >> 2) & 0x03) != 0x03)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    } 
    else
    {

    return 0;
    }
}

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