Macro-Based Register Config Helper

Code

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

/* Bit positions and masks */
#define ENABLE_POS   0
#define MODE_POS     1
#define SPEED_POS    3

#define ENABLE_MASK  (1U << ENABLE_POS)
#define MODE_MASK    (3U << MODE_POS)
#define SPEED_MASK   (7U << SPEED_POS)

/* Macros to set fields */
#define SET_ENABLE(reg, val) \
    ((reg) |= (((val) & 0x1U) << ENABLE_POS))

#define SET_MODE(reg, val) \
    ((reg) |= (((val) & 0x3U) << MODE_POS))

#define SET_SPEED(reg, val) \
    ((reg) |= (((val) & 0x7U) << SPEED_POS))

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    uint16_t reg = 0;

    SET_ENABLE(reg, enable);
    SET_MODE(reg, mode);
    SET_SPEED(reg, 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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37