Macro-Based Register Config Helper

Code

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

// Define macros here
#define ENABLE 0
#define MODE 1
#define SPEED 3
#define RESERVED 6
#define WRITEBIT(WORD,BITPOS,BIT) WORD=((WORD&~(1<<BITPOS))|(BIT<<BITPOS))

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    uint16_t val=0;
    WRITEBIT(val,ENABLE,enable);
    WRITEBIT(val,MODE,mode);
    WRITEBIT(val,SPEED,speed);
    return 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

 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37