77. Validate Configuration Register Layout

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

typedef struct {
    unsigned short reg;
} ConfigRegister;

typedef union {
    unsigned short buf;
    struct {
        unsigned short Enable:1;
        unsigned short Mode: 1;
        unsigned short Priority: 2;
        unsigned short Reserved: 12;
    }fields;
}ctrl_reg;

int validate_config(ConfigRegister *cfg) {
    // Write logic using pointer access
    unsigned short buf = cfg->reg;
    ctrl_reg reg_u;
    reg_u.buf = buf;

    if (reg_u.fields.Enable == 1 && reg_u.fields.Priority != 0x3 && reg_u.fields.Reserved == 0)
        return 1;
    return 0;
}

int main() {
    ConfigRegister cfg;
    scanf("%hx", &cfg.reg);

    int result = validate_config(&cfg);
    printf("%d", result);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote