All submissions

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) 
{
    char a=(ctrl->reg)&1; /* Checking if lastbit is set or not */
    char b=(ctrl->reg)>>2; /* Extracting Bit2 and Bit3 and checking if extracted value <=2*/
    b=b&3;
    char c=(ctrl->reg)>>4; /*Perfoming rightshift by 4 times to get MSB nibble and checking if it matches zero.*/
    c=c&15;
    if( a && b<=2 && !c ) 
     return 1;


    return 0;
}

int main() {
    ControlRegister ctrl;
    scanf("%hhx", &ctrl.reg);

    int result = validate_register(&ctrl);
    printf("%d", result);

    return 0;
}

Solving Approach

1: We need to create 3 flags for understanding each condition.

    flag1 for checking enable or not.

2: Flag2 for checking priority by extracting Bit2 and Bit3 value.

3: Flag3 for checking reserved bits, we need to extract MSB nibble and check if it matches zero or

we can also use condition !flag3 which will be true if reserved bit(MSB nibble) is zero.

 

 

Loading...

Input

05

Expected Output

1