Extract and Modify Field in a 32-bit Register

Code

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

uint32_t update_register(uint32_t reg) {
    
    // 1. Extract the field
    // Shift right so bit 10 becomes bit 0, then mask to 5 bits.
    uint32_t field_value = (reg >> 10) & 0x1F;

    // 2. Modify the field
    if(field_value < 31) 
    field_value++;

    // 3. Clear the original bits 10-14
    // ~(0x1F << 10) creates a mask with 0s only at bits 10-14
    reg &= ~(0x1F << 10);

    // 4. Write the updated value back
    reg |= (field_value << 10);
    
    return reg;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

15360

Expected Output

16384