Pack Multiple Fields into a 16-bit Control Register

Code

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

#define SET_FIELD(value, mask, shift)   (((value) & (mask)) << (shift))

#define SET_MODE(x)     SET_FIELD(x, 0b111,     0)   // bits 0-2
#define SET_SPEED(x)    SET_FIELD(x, 0b11111,    3)   // bits 3-6
#define SET_STATUS(x)   SET_FIELD(x, 0b111111, 10)   // bits 10-15


uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    

    return SET_MODE(mode) | SET_SPEED (speed) | SET_STATUS(status);
}

int main() {
    uint8_t mode, speed, status;
    scanf("%hhu %hhu %hhu", &mode, &speed, &status);

    uint16_t reg = pack_register(mode, speed, status);
    printf("%u", reg);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

3 10 12

Expected Output

12371