Decode Status Register into Human-Readable Flags

Code

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

// La fonction qui décode et affiche les flags.
void decode_status(uint8_t status_reg) {
    // Tableau qui mappe chaque bit (indice) à sa signification.
    const char* flag_names[] = {
        "Power On",
        "Error",
        "Tx Ready",
        "Rx Ready",
        "Overheat",
        "Undervoltage",
        "Timeout",
        "Reserved"
    };

    // On parcourt chaque bit du registre, de 0 (LSB) à 7 (MSB).
    for (int i = 0; i < 8; i++) {
        // On crée un masque pour le bit 'i'.
        uint8_t mask = 1 << i;

        // Si le bit 'i' est activé dans le registre...
        if (status_reg & mask) {
            // ...on affiche le nom du flag correspondant.
            printf("%s\n", flag_names[i]);
        }
    }
}

int main() {
    uint8_t status_reg;
    
    // Lit la valeur du registre fournie par l'utilisateur.
    // %hhu est le format correct pour lire un uint8_t.
    scanf("%hhu", &status_reg);
    
    // Appelle la fonction pour effectuer le décodage.
    decode_status(status_reg);
    
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

13

Expected Output

Power On Tx Ready Rx Ready