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>

#define CR_MODE_Pos 0U
#define CR_MODE_Msk (0x7U << CR_MODE_Pos)
#define CR_MODE CR_MODE_Msk
#define CR_SPEED_Pos 3U
#define CR_SPEED_Msk (0x1FU << CR_SPEED_Pos)
#define CR_SPEED CR_SPEED_Msk
#define CR_STATUS_Pos 10U
#define CR_STATUS_Msk (0x3FU << CR_STATUS_Pos)
#define CR_STATUS CR_STATUS_Msk

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    return ((mode << CR_MODE_Pos) & CR_MODE_Msk)
            | ((speed << CR_SPEED_Pos) & CR_SPEED_Msk) 
            | ((status << CR_STATUS_Pos) & CR_STATUS_Msk);
}

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