Macro-Based Register Config Helper

Code

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

// Define macros for bit positions
#define ENABLE_SHIFT 0
#define MODE_SHIFT   1
#define SPEED_SHIFT  3

// Define macros for bit masks (pre-shift)
#define ENABLE_MASK  0x01
#define MODE_MASK    0x03
#define SPEED_MASK   0x07

// Macro to pack a field: (value & mask) << shift
#define SET_ENABLE(val) (((val) & ENABLE_MASK) << ENABLE_SHIFT)
#define SET_MODE(val)   (((val) & MODE_MASK)   << MODE_SHIFT)
#define SET_SPEED(val)  (((val) & SPEED_MASK)  << SPEED_SHIFT)

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Combine the fields using bitwise OR
    // Reserved bits 6-7 are implicitly 0 because no macro targets those shifts
    uint16_t reg = 0;
    
    reg |= SET_ENABLE(enable);
    reg |= SET_MODE(mode);
    reg |= SET_SPEED(speed);
    
    return reg;
}

int main() {
    uint8_t enable, mode, speed;
    if (scanf("%hhu %hhu %hhu", &enable, &mode, &speed) == 3) {
        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