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) {
    unsigned char reg = ctrl->reg;
    if ((reg&1) != 1){ // Check for enable
        return 0;
    }

    unsigned char priority = (reg & 0xC) >> 2;
    if ((int)priority == 3){
        return 0;
    }

    unsigned char reserved = (reg & 0xF0) >> 4;
    if ((int)reserved !=0){
        return 0;
    }

    return 1;
}

// 0000 0000

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