All submissions

Pack Multiple Fields into a 16-bit Control Register

Use bitwise shifts

#include <stdio.h>
#include <stdint.h>
/*  alternate way using unions
union packed{
    struct{
        uint16_t mode : 3;
        uint16_t spd : 5;
        uint16_t res : 2;
        uint16_t stat : 6;
    };
    uint16_t raw;
};

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    packed pack;
    pack.mode = mode;
    pack.spd = speed;
    pack.res = 0;
    pack.stat = status;
    return pack.raw;
}
*/
uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    uint16_t result;
    result |= mode | (speed << 3) | (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

 

 

 

Loading...

Input

3 10 12

Expected Output

12371