59. Pack Multiple Fields into a 16-bit Control Register

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

uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
    uint16_t reg = 0;

    // Validate input limits
    if (mode > 7) mode = 7;         // 3 bits max
    if (speed > 31) speed = 31;     // 5 bits max
    if (status > 63) status = 63;   // 6 bits max

    reg |= (mode & 0x07);           // Bits 0–2
    reg |= (speed & 0x1F) << 3;     // Bits 3–7
    // Bits 8–9 (Reserved) left as 0
    reg |= (status & 0x3F) << 10;   // Bits 10–15

    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;
}

🧠 What Is Bitfield Packing?

Firmware developers often combine multiple config fields into a single register using bitwise operations. This mimics real hardware control registers.

🎯 Why It Matters?

  • Saves memory
  • Matches peripheral register layout
  • Needed when writing to hardware control registers
     

🔧 Solution Logic

  • Use bit masks to limit each field
  • Use bitwise OR (|=) to insert each field at the correct bit position
  • Reserved bits are skipped (set to 0)
     
Loading...

Input

3 10 12

Expected Output

12371