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 5-bit field at positions 10-14
    // Shift right by 10 to bring the field to the LSB position
    // Mask with 0x1F (binary 11111) to isolate the 5 bits
    uint32_t field = (reg >> 10) & 0x1F;

    // 2. Modify: Increment if less than 31
    if (field < 31) {
        field++;
    }

    // 3. Clear the original bits 10-14 in the register
    // 0x1F << 10 creates a mask of 1s at bits 10-14. 
    // The ~ (NOT) operator turns them to 0s and everything else to 1s.
    reg &= ~(0x1F << 10);

    // 4. Update: Write the modified field back into the register
    reg |= (field << 10);

    return reg;
}

int main() {
    uint32_t reg;
    // Note: Using %u for unsigned int, though 0x hex inputs 
    // usually prefer %x or %i for flexibility.
    if (scanf("%u", &reg) == 1) {
        uint32_t updated = update_register(reg);
        printf("%u\n", updated);
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

15360

Expected Output

16384