Decode Status Register into Human-Readable Flags

Code

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

/*
In embedded systems, status registers often represent multiple flags using each bit. You are given an 8-bit status register. Each bit corresponds to a different condition.

Bit-to-Flag Mapping

Bit	Meaning
0	Power On
1	Error
2	Tx Ready
3	Rx Ready
4	Overheat
5	Undervoltage
6	Timeout
7	Reserved

*/

#define BIT(n) (1 << n)

void decode_status(uint8_t status_reg)
{
    if (status_reg & (BIT(0)))
    {
        printf("Power On\n");
    }
    if (status_reg & (BIT(1)))
    {
        printf("Error\n");
    }
    if (status_reg & (BIT(2)))
    {
        printf("Tx Ready\n");
    }
    if (status_reg & (BIT(3)))
    {
        printf("Rx Ready\n");
    }
    if (status_reg & (BIT(4)))
    {
        printf("Overheat\n");
    }
    if (status_reg & (BIT(5)))
    {
        printf("Undervoltage\n");
    }
    if (status_reg & (BIT(6)))
    {
        printf("Timeout\n");
    }
    if (status_reg & (BIT(7)))
    {
        printf("Reserved\n");
    }
}

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