Decode Status Register into Human-Readable Flags

Code

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

#define BIT_POWER_ON 0 
#define BIT_ERROR 1 
#define BIT_TX_READY 2 
#define BIT_RX_READY 3 
#define BIT_OVERHEAT 4 
#define BIT_UNDERVOLTAGE 5 
#define BIT_TIMEOUT 6 
#define BIT_RESERVED 7 

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

void decode_status(uint8_t status_reg) {
    if (status_reg & BIT(BIT_POWER_ON)) printf("Power On\n");
    if (status_reg & BIT(BIT_ERROR)) printf("Error\n");
    if (status_reg & BIT(BIT_TX_READY)) printf("Tx Ready\n");
    if (status_reg & BIT(BIT_RX_READY)) printf("Rx Ready\n");
    if (status_reg & BIT(BIT_OVERHEAT)) printf("Overheat\n");
    if (status_reg & BIT(BIT_UNDERVOLTAGE)) printf("Undervoltage\n");
    if (status_reg & BIT(BIT_TIMEOUT)) printf("Timeout\n");
    if (status_reg & BIT(BIT_RESERVED)) 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