60. Extract and Modify Field in a 32-bit Register

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

uint32_t update_register(uint32_t reg) {
    uint32_t mask = 0x1F << 10; // 5-bit field at bits 10–14
    uint32_t field = (reg & mask) >> 10; // Extract field

    if (field < 31) {
        field += 1; // Increment
    }

    reg &= ~mask; // Clear bits 10–14
    reg |= (field << 10); // Write updated field

    return reg;
}

int main() {
    uint32_t reg;
    scanf("%u", &reg);
    uint32_t updated = update_register(reg);
    printf("%u", updated);
    return 0;
}

What is happening here?

This simulates a real-world case where a specific field inside a hardware register (bit positions 10–14) needs to be updated — without affecting other bits. It’s a common task in firmware when managing peripheral modes, status, or flags.

Why it’s important in firmware?

  • You must often manipulate only a portion of a register
  • Accidental overwrite of other fields can cause hardware issues
  • Bit masking and shifting ensures precise field-level control

Solution Logic

  • Mask the 5-bit field from bits 10–14 using (reg & mask)
  • Increment if value is less than 31
  • Clear old field bits using reg &= ~mask
  • Insert updated field with reg |= field << 10
     
Loading...

Input

15360

Expected Output

16384