Macro-Based Register Config Helper

Code

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

typedef struct {
    uint16_t position;
    uint16_t bits;
} Field_t; 

 typedef enum {
    ENABLE,
    MODE,
    SPEED,
    RESERVED,
    TOTAL_FIELDS
 } FieldType;

// Define macros here
static inline void _setField(uint16_t *reg, const FieldType FieldType, const uint8_t FieldData);

static const Field_t _Fields[TOTAL_FIELDS] = {
    { .position = 0, .bits = 1 },
    { .position = 1, .bits = 2 },
    { .position = 3, .bits = 3 },
    { .position = 6, .bits = 2 }
};

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    uint16_t reg = 0;

    _setField(&reg, ENABLE, enable);
    _setField(&reg, MODE,   mode);
    _setField(&reg, SPEED,  speed);

    return reg;
}

int main() {
    uint8_t enable, mode, speed;
    scanf("%hhu %hhu %hhu", &enable, &mode, &speed);

    uint16_t reg = build_register(enable, mode, speed);
    printf("%u", reg);
    return 0;
}

static inline void _setField(uint16_t *reg, const FieldType Type, const uint8_t Data)
{
    if (reg)
    {
        const Field_t *field = &_Fields[Type];

        *reg |= (Data << field->position);
    }
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37