77. Validate Configuration Register Layout

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

typedef struct {
    union{
        unsigned short reg;
        struct {
            unsigned enable : 1;
            unsigned mode   : 1;
            unsigned priority : 2;
            unsigned reserved : 12;
        } bits;
    };
} ConfigRegister;

// int validate_config(ConfigRegister *cfg) {

//     if ( ((cfg->reg & 0x1) && (((cfg->reg >> 2) && 0x3) != 11) && ((cfg->reg) >> 4) == 0) ){
//         return 1;
//     }
//     return 0;
// }

int validate_config(ConfigRegister *cfg) {
    // Write logic using pointer access
    //printf("%d %d %d\n", cfg->bits.enable, cfg->bits.priority, cfg->bits.reserved);
    if (cfg->bits.enable != 1)
        return 0;
    if (cfg->bits.priority == 3)
        return 0;
    if (cfg->bits.reserved != 0)
        return 0;
    return 1;
}

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