25. Pack Multiple Fields into a 16-bit Control Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    uint16_t reg = 0;
    // Set status bits
    reg |= ((status & 0x003F) << 10);
    // Set reserved bits to 0 - for hygiene
    reg |= (0x00 << 8);
    // Set speed bits
    reg |= ((speed & 0x001F) << 3);
    // Set mode bits
    reg |= (mode & 0x0007);
    return 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

 

 

 

Was this helpful?
Upvote
Downvote