Pack Multiple Fields into a 16-bit Control Register

Code

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

#define MODE_MASK 0x07
#define SPEED_MASK 0xF8
#define RESERVED_MASK 0x0300
#define STATUS_MASK 0xFC00

#define SET_MODE(REG,VAL)((REG & ~MODE_MASK)|((VAL & 0x7) << 0))
#define SET_SPEED(REG,VAL)((REG & ~SPEED_MASK)|((VAL & 0x1F) << 3))
#define SET_RESERVED(REG,VAL)((REG & ~RESERVED_MASK)|((VAL & 0x3) << 8))
#define SET_STATUS(REG,VAL)((REG & ~STATUS_MASK)|((VAL & 0x3F) << 10))
uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    
    return (SET_MODE(0,mode)|SET_SPEED(0,speed)|SET_RESERVED(0,0)|SET_STATUS(0,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