Macro-Based Register Config Helper

Code

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

// Define macros here
/* Bit Positions */
#define ENABLE_POS   0
#define MODE_POS     1
#define SPEED_POS    3

/* Field Masks (before shifting) */
#define ENABLE_MASK  0x1U      // 1 bit
#define MODE_MASK    0x3U      // 2 bits
#define SPEED_MASK   0x7U      // 3 bits

/* Macros to Set Fields */
#define SET_ENABLE(val)  (((uint16_t)((val) & ENABLE_MASK)) << ENABLE_POS)
#define SET_MODE(val)    (((uint16_t)((val) & MODE_MASK)) << MODE_POS)
#define SET_SPEED(val)   (((uint16_t)((val) & SPEED_MASK)) << SPEED_POS)

/* Macros to Read Fields */
#define GET_ENABLE(reg)  (((reg) >> ENABLE_POS) & ENABLE_MASK)
#define GET_MODE(reg)    (((reg) >> MODE_POS) & MODE_MASK)
#define GET_SPEED(reg)   (((reg) >> SPEED_POS) & SPEED_MASK)

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

    reg |= SET_ENABLE(enable);
    reg |= SET_MODE(mode);
    reg |= SET_SPEED(speed);

    return reg;   // RESERVED bits (6–7) remain 0
}

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