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>

struct Register{
    uint8_t Mode : 3;
    uint8_t Speed : 5;
    uint8_t Reserved : 2;
    uint8_t Status : 6;
};

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

    reg |= (mode & 0x7) << 0;        // bits 0–2
    reg |= (speed & 0x1F) << 3;      // bits 3–7 are not masked from speed  then to fit in reg we should move them up 3 bits 
    reg |= (status & 0x3F) << 10;    // bits 10–15
    // reserved bits 8–9 remain 0 automatically

    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