Pack Multiple Fields into a 16-bit Control Register

Code

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

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    uint16_t reg = 0;

    // 1. Pack Mode into Bits 0–2
    // Masking with 0x07 (binary 111) ensures we only use 3 bits.
    reg |= (mode & 0x07);

    // 2. Pack Speed into Bits 3–7
    // Masking with 0x1F (binary 11111) ensures we only use 5 bits, then shift left by 3.
    reg |= ((speed & 0x1F) << 3);

    // 3. Bits 8-9 are Reserved (must be 0)
    // Since reg was initialized to 0, these remain 0 automatically.

    // 4. Pack Status into Bits 10–15
    // Masking with 0x3F (binary 111111) ensures 6 bits, then shift left by 10.
    reg |= ((status & 0x3F) << 10);

    return reg;
}

int main() {
    uint8_t mode, speed, status;
    if (scanf("%hhu %hhu %hhu", &mode, &speed, &status) == 3) {
        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