Macro-Based Register Config Helper

Code

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

// Define macros here

#define ENABLE_POS 0
#define MODE_POS 1
#define SPEED_POS 3

#define ENABLE_MASK 0x1 // 1 bit 1
#define MODE_MASK 0x3 // 2 bit 11
#define SPEED_MASK 0x7 // 3 bit 111

#define SET_ENABLE(x) (((x) & ENABLE_MASK) << ENABLE_POS)
#define SET_MODE(x) (((x) & MODE_MASK) << MODE_POS)
#define SET_SPEED(x) (((x) & SPEED_MASK) << SPEED_POS)



uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    return SET_ENABLE(enable) | SET_MODE(mode) | SET_SPEED(speed);
}

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