Macro-Based Register Config Helper

Code

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

// ───────────────────────────────────────────────
//              Register Field Macros
// ───────────────────────────────────────────────

// Positions and masks
#define ENABLE_POS       0
#define ENABLE_MASK      (1u << ENABLE_POS)

#define MODE_POS         1
#define MODE_WIDTH       2
#define MODE_MASK        (((1u << MODE_WIDTH) - 1) << MODE_POS)

#define SPEED_POS        3
#define SPEED_WIDTH      3
#define SPEED_MASK       (((1u << SPEED_WIDTH) - 1) << SPEED_POS)

// Field value preparation macros (safe: mask input to correct width)
#define ENABLE_BIT(val)     (((val) & 1u) << ENABLE_POS)
#define MODE_BITS(val)      (((val) & 0x3u) << MODE_POS)     // 0–3
#define SPEED_BITS(val)     (((val) & 0x7u) << SPEED_POS)    // 0–7

// Most convenient way: build full register value in one expression
#define BUILD_CONTROL_REG(en, md, sp)   ( \
    ENABLE_BIT(en) | \
    MODE_BITS(md)  | \
    SPEED_BITS(sp)   \
)

// ───────────────────────────────────────────────

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Build the register value using the macro (reserved bits stay 0)
    uint16_t reg = BUILD_CONTROL_REG(enable, mode, speed);
    return reg;
}

int main() {
    uint8_t enable_val, mode_val, speed_val;

    // Read three values from input
    if (scanf("%hhu %hhu %hhu", &enable_val, &mode_val, &speed_val) != 3) {
        printf("Invalid input\n");
        return 1;
    }

    uint16_t reg = build_register(enable_val, mode_val, speed_val);
    printf("%u\n", reg);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37