Pack Multiple Fields into a 16-bit Control Register

Code

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

typedef enum {
    MODE = 0,      // bits 0-2
    SPEED = 3,     // bits 3-7
    RESERVED = 8,  // bits 8-9
    STATUS = 10    // bits 10-15
} FIELD;

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    uint16_t value = 0;
    // Pack các field
    value |= (mode << MODE);
    value |= (speed << SPEED);
    value |= (status << STATUS);

    // Clear 2 reserved bits
    value &= ~(0b11 << RESERVED);

    return value;
}

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

    uint16_t reg = pack_register(mode, speed, status);
    printf("%u\n", reg);  // in decimal
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

3 10 12

Expected Output

12371