All submissions

Macro-Based Register Config Helper

Code

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

// Define macros here

typedef union{
    uint16_t reg;

    struct{
        uint16_t enable : 1;
        uint16_t mode: 2; 
        uint16_t speed: 3; 
        uint16_t reserved: 10;  
    }bits;

}REG_CONFIG_T;


#define REG_CONFIG_ENABLE_MASK   (0x1u << 0)
#define REG_CONFIG_MODE_MASK     (0x3u << 1)
#define REG_CONFIG_SPEED_MASK    (0x7u << 3)

#define REG_CONFIG_SET_ENABLE(reg, value) \
    (((reg) & ~REG_CONFIG_ENABLE_MASK) | (((value) & 0x1u) << 0))

#define REG_CONFIG_SET_MODE(reg, value) \
    (((reg) & ~REG_CONFIG_MODE_MASK) | (((value) & 0x3u) << 1))

#define REG_CONFIG_SET_SPEED(reg, value) \
    (((reg) & ~REG_CONFIG_SPEED_MASK) | (((value) & 0x7u) << 3))


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

    config.reg = REG_CONFIG_SET_ENABLE(config.reg, enable);
    config.reg = REG_CONFIG_SET_MODE(config.reg, mode);
    config.reg = REG_CONFIG_SET_SPEED(config.reg, speed); 

    return config.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

 

 

 

Loading...

Input

1 2 4

Expected Output

37