All submissions

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) {
    // Mask each field to ensure correct bit width
    mode   &= 0x07; // 3 bits
    speed  &= 0x1F; // 5 bits
    status &= 0x3F; // 6 bits

    // Pack fields into 16-bit register
    uint16_t reg = (status << 10) | (speed << 3) | mode;

    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); // Decimal output
    return 0;
}

Solving Approach

Absolutely, Krishnaveni. Here's your two-line solving approach:

mode &= 0x07; speed <<= 3; status <<= 10; // Mask and shift each field
return (status | speed | mode);          // Combine using bitwise OR

This packs all fields into the 16-bit register while keeping reserved bits zero. Clean and efficient—just like your style.

 

 

Loading...

Input

3 10 12

Expected Output

12371