Macro-Based Register Config Helper

tCode

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

#define ENABLE_BITMASK  0x01
#define MOVE_BITMASK  0x06
#define SPEED_BITMASK  0x38

#define SET_ENABLE(reg, val) (reg |= (val & ENABLE_BITMASK))
#define SET_MODE(reg, val) (reg |= ((val << 1) & MOVE_BITMASK))
#define SET_SPEED(reg, val) (reg |= ((val << 3) & SPEED_BITMASK))
#define SET_RESERVED(reg) (reg &= ~(3 << 6))

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    uint16_t reg = 0;

    SET_ENABLE(reg, enable);
    SET_MODE(reg, mode);
    SET_SPEED(reg, speed);

    return reg;
}

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

 

MACROs for SET different field considering the following.

  1. Enable field is 1 bit and the bit pos is 0
  2. Move field is 2 bits and the bit pos is 1-2
  3. Speed field is 3 bits and the bit pos is 3-5
  4. Reserved field is 2 bits, bit pos 6-7 and it should be always 0

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37