All submissions

Pack Multiple Fields into a 16-bit Control Register

Code

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

#define MASK1(mode)         (mode << 0U)
#define MASK2(speed)        (speed << 3U)
#define MASK3               (0 << 8U)
#define MASK4(status)       (status << 10)

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    // Your logic here
    uint16_t result = 0x0000;
    result |=  MASK1(mode) + MASK2(speed) + MASK3 + MASK4(status);

    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

/*
16 bit CR
- Mode (0-2)
- Speed (3-7)
- Reserved (8-9) -> should be 0
- Status (10-15)

Example:
Input: mode = 3, speed = 10, status = 12
Output: 12371
(Hex: 0x3053, Binary: 0011_0000_0101_0011)
0-2 -> 0011 (3 in decimal)
3-7 -> 1010 (10 in decimal)
8-9 -> 0
10-15 -> 1100 (12 in decimal)

Plan:
- mask 1 : shift the mode value by 0 to the left
- mask 2 : shift the speed value by 3 to the left
- mask 3 : shift the 0 value by 8 to the left
- mask 4 : shift the status value by 10 to the left

*/

 

 

Loading...

Input

3 10 12

Expected Output

12371