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) {
    // Your logic here
    uint16_t val;
    //input limit set
    if(mode > 7) mode =7; //0b111
    if(speed > 31) speed=31; //0b11111
    if(status > 63) status=63; //0b111111

    //set the bits in the position

    val |= (mode & 0x07); //bits 0 to 2
    val |= (speed & 0x1f) << 3; //bits 3 to 7
    val |= (status & 0x3f) <<10; //bits 10 to 15

    return val;
}

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

 

 

 

Upvote
Downvote
Loading...

Input

3 10 12

Expected Output

12371