Pack Multiple Fields into a 16-bit Control Register

Code

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

#define MODE_pos        (0)
#define SPEED_pos       (3)
#define RESERVED_pos    (8)
#define STATUS_pos      (10)

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    uint16_t temp_reg = 0;

    temp_reg |= (uint16_t)((mode & 0x07) << MODE_pos);
    temp_reg |= (uint16_t)((speed & 0x3F) << SPEED_pos);
    temp_reg &= ~(uint16_t)(0x03 << RESERVED_pos);
    temp_reg |= (uint16_t)((status & 0x7F) << STATUS_pos);
    return temp_reg;
}

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