All submissions

Macro-Based Register Config Helper

Code

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

// Define macros here
#define ENABLE_BIT_POS (0)
#define ENABLE_BIT_BITS (1)
#define ENABLE_BIT_MASK (((1U<<(ENABLE_BIT_BITS))-1)<<ENABLE_BIT_POS)

#define MODE_FIELD_POS (1)
#define MODE_FIELD_BITS (2)
#define MODE_FIELD_MASK (((1U<<(MODE_FIELD_BITS))-1)<<MODE_FIELD_POS)

#define SPEED_FIELD_POS (3)
#define SPEED_FIELD_BITS (3)
#define SPEED_FIELD_MASK (((1U<<(SPEED_FIELD_BITS))-1)<<SPEED_FIELD_POS)

#define SET_ENABLE_BIT(var,val) ((var)=((var)&(~ENABLE_BIT_MASK))|((val<<ENABLE_BIT_POS)&ENABLE_BIT_MASK))
#define SET_MODE_FIELD(var,val) ((var)=((var)&(~MODE_FIELD_MASK))|((val<<MODE_FIELD_POS)&MODE_FIELD_MASK))
#define SET_SPEED_FIELD(var,val) ((var)=((var)&(~SPEED_FIELD_MASK))|((val<<SPEED_FIELD_POS)&SPEED_FIELD_MASK))

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    uint16_t ret_val =0;
    SET_ENABLE_BIT(ret_val,enable);
    SET_MODE_FIELD(ret_val,mode);
    SET_SPEED_FIELD(ret_val,speed);
    return ret_val;
}

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