Decode Status Register into Human-Readable Flags

Code

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

void decode_status(uint8_t status_reg) {
    // Array mapping bit index to its human-readable name
    const char *flags[] = {
        "Power On",
        "Error",
        "Tx Ready",
        "Rx Ready",
        "Overheat",
        "Undervoltage",
        "Timeout",
        "Reserved"
    };

    // Iterate through each bit (0 to 7)
    for (int i = 0; i < 8; i++) {
        // Use a bitmask to check if the i-th bit is set
        // (1 << i) creates a value with only the i-th bit as 1
        if (status_reg & (1 << i)) {
            printf("%s\n", flags[i]);
        }
    }
}

int main() {
    uint8_t reg;
    // Using %hhu to specifically read into an unsigned 8-bit char
    if (scanf("%hhu", &reg) == 1) {
        decode_status(reg);
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

13

Expected Output

Power On Tx Ready Rx Ready