Decode Status Register into Human-Readable Flags

Code

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

char flags[8][13] = 
{
    "Power On",
    "Error",
    "Tx Ready",
    "Rx Ready",
    "Overheat",
    "Undervoltage",
    "Timeout",
    "Reserved"
};

uint8_t strip_rightmost_bit(uint8_t val) 
{
    if (val == 0)
    {
        return (uint8_t)0;
    }

    uint8_t isolated = val & -val;

    uint8_t pos = 0;

    if (isolated & 0xFFFF0000) pos += 16;
    if (isolated & 0xFF00FF00) pos += 8;
    if (isolated & 0xF0F0F0F0) pos += 4;
    if (isolated & 0xCCCCCCCC) pos += 2;
    if (isolated & 0xAAAAAAAA) pos += 1;

    return pos;
}

void decode_status(uint8_t status_reg) 
{
    while (status_reg)
    {
        uint8_t val = strip_rightmost_bit(status_reg);
        status_reg -= (1 <<val);
        printf("%s\n", flags[val]);
    }
    
}

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