Decode Status Register into Human-Readable Flags

Code

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

// Bit definitions
#define STATUS_POWER_ON       (1U << 0)
#define STATUS_ERROR          (1U << 1)
#define STATUS_TX_READY       (1U << 2)
#define STATUS_RX_READY       (1U << 3)
#define STATUS_OVERHEAT       (1U << 4)
#define STATUS_UNDERVOLTAGE   (1U << 5)
#define STATUS_TIMEOUT        (1U << 6)
#define STATUS_RESERVED       (1U << 7)

// Macro to check if a bit is set
#define CHECK_BIT(REG,BIT) ((REG) & (BIT))

void decode_status(uint8_t status_reg) {
    // Array of flag names, order = bit position
    const char* flag_names[] = {
        "Power On", "Error", "Tx Ready", "Rx Ready",
        "Overheat", "Undervoltage", "Timeout", "Reserved"
    };

    // Array of bit masks
    const uint8_t bit_masks[] = {
        STATUS_POWER_ON, STATUS_ERROR, STATUS_TX_READY, STATUS_RX_READY,
        STATUS_OVERHEAT, STATUS_UNDERVOLTAGE, STATUS_TIMEOUT, STATUS_RESERVED
    };

    for(int i = 0; i < 8; i++) {
        if(CHECK_BIT(status_reg, bit_masks[i]))
            printf("%s\n", flag_names[i]);
    }
}

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