Macro-Based Register Config Helper

Code

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

/*Your task is to:
 - Write macros to: 
+ Set the ENABLE bit
+ Set the MODE field
+ Set the SPEED field
+ Read ENABLE, MODE, SPEED from input
+ Use the macros to pack a final 16-bit register value
RESERVED bits (6–7) must be left 0 */ 

// Define macros here
#define SET_ENABLE(reg,x) reg | (uint16_t)((x))
#define SET_MODE(reg,x)   reg | ((uint16_t)((x)) << 1) 
#define SET_SPEED(reg,x)  reg | ((uint16_t)((x)) << 3)     

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    uint16_t x = 0; 
    if(enable > 1) return 0; 
    if((mode > 4) || (speed > 8)) return 0; 
    x = SET_ENABLE(x,enable);
    x = SET_MODE(x,mode);
    x = SET_SPEED(x,speed); 
    return x; 
}

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