Decode Status Register into Human-Readable Flags

Code

#include <stdio.h>
#include <stdint.h>

enum state{
    POWER_ON        = 1,
    ERROR           = 2,
    TX_READY        = 4,
    RX_READY        = 8,
    OVERHEAT        = 16,
    UNDERVOLTAGE    = 32,
    TIMEOUT         = 64,
    RESERVED        = 128,
};

void decode_status(uint8_t status_reg) {
    // Your logic here
    for(int i = 0; i < 8; i++)
    {
        switch(((1U << i) & status_reg))
        {
            case POWER_ON:
                printf("Power On\n");
                break;
            case ERROR:
                printf("Error\n");
                break;
            case TX_READY:
                printf("Tx Ready\n");
                break;
            case RX_READY:
                printf("Rx Ready\n");
                break;
            case OVERHEAT:
                printf("Overheat\n");
                break;
            case UNDERVOLTAGE:
                printf("Undervoltage\n");
                break;
            case TIMEOUT:
                printf("Timeout\n");
                break;
            case RESERVED:
                printf("Reserved\n");
                break;            
        }
    }
}

int main() {
    uint8_t reg;
    scanf("%hhu", &reg);
    decode_status(reg);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

13

Expected Output

Power On Tx Ready Rx Ready