Macro-Based Register Config Helper

Code

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


// my logic
// Define macros here
// #define ENABLE(r, n)    ((r) |= n)
// #define MODE(r, n)    ((r) |= (n << 1))
// #define SPEED(r, n)    ((r) |= (n << 3))

// uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
//     // Use macros to set fields
//     uint16_t ret = 0;
    
//     ENABLE(ret, enable);
//     MODE(ret, mode);
//     SPEED(ret, speed);

//     return ret;
// }

// Solution
// Define macros here
#define SET_ENABLE(x)  ((x & 0x01) << 0)   // Bit 0
#define SET_MODE(x)    ((x & 0x03) << 1)   // Bits 1–2
#define SET_SPEED(x)   ((x & 0x07) << 3)   // Bits 3–5


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

    return ret;
}

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

(x & 0x0n) in the #define are protection logic

Solution is more clear than my code

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37