All submissions

Pack Multiple Fields into a 16-bit Control Register

Code

#include <stdio.h>
#include <stdint.h>

#define MASK(BITS) ((1U << BITS)-1)
#define SHIFTED_MASK(POS, BITS) (MASK(BITS) << (POS))
#define CLEAR_BITS(REG, POS, BITS)  \
((REG) = (REG) & ~(SHIFTED_MASK(POS, BITS)))
#define SET_BITS(REG, POS, BITS, VAL)   \
(REG) = ((REG) & ~(SHIFTED_MASK(POS, BITS))) | ((VAL & MASK(BITS)) << POS)


uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    uint16_t reg = 0;
    SET_BITS(reg, 0, 3, mode);
    SET_BITS(reg, 3, 5, speed);
    SET_BITS(reg, 10, 6, status);
    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

 

 

 

Loading...

Input

3 10 12

Expected Output

12371