Macro-Based Register Config Helper

Code

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

// Define macros here
#define ENABLE(x) ((x & 0x01))
#define MODE(x) ((x & 0x03) << 1)
#define SPEED(x) ((x & 0x07) << 3)

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    uint16_t reg_out;
    reg_out = ENABLE(enable) | MODE(mode) | SPEED(speed);
    return reg_out;
}

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

The code is simple. It has a function that builds a 16-bit value and stores it in a 16-bit variable using Macros and OR operation. This variable's value is then accessed through the main function wherein we obtain which bit should be made high as an unsigned 8-bit input from the user.  

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37