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 result ;
     result|=0x07&mode;
     result|=(0x1F&speed)<<3;
     result=result&~(0x3<<8);
     result|=(0x3f&status)<<10;
    return result;
}

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

create the mask for each field with len 111... and take AND with the value and then apply the value to each field accordingly.

 

 

Was this helpful?
Upvote
Downvote