Macro-Based Register Config Helper

Code

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

#define EN(enable, x) (x |= (((enable) & 1) << 0))  // Mask 1 bit and shift to position 0, OR with output
#define MODE(mode, x) (x |= (((mode) & 3) << 1)) // Mask 2 bits and shift to positions 1-2, OR with output
#define SPEED(speed, x) (x |= (((speed) & 7) << 3)) // Mask 3 bits and shift to positions 3-5, OR with output

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    uint16_t output = 0; // Create a 16 output register
    EN(enable, output);
    MODE(mode, output);
    SPEED(speed, output);
    return output;
}

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