#include <stdint.h>
#include <stdio.h>
// Macro to define the bit position of a field
#define FIELD_POSITION(field) field##_POS
// Macro to define the bit width of a field
#define FIELD_WIDTH(field) field##_WID
// Macro to create a value masked and shifted correctly for a field
#define FIELD_VAL(field, value) \
(((value) & ((1 << FIELD_WIDTH(field)) - 1)) << FIELD_POSITION(field))
// Define the position and width for each field based on the layout above
#define ENABLE_POS 0
#define ENABLE_WID 1
#define MODE_POS 1
#define MODE_WID 2
#define SPEED_POS 3
#define SPEED_WID 3
uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
uint16_t reg = 0;
// Use the macros to set each field in the register
reg |= FIELD_VAL(ENABLE, enable);
reg |= FIELD_VAL(MODE, mode);
reg |= FIELD_VAL(SPEED, 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;
}
Input
1 2 4
Expected Output
37