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 value using a mask
    // 2) check if value is < 31. if so increment it. 
    // 3) return reg

    const uint8_t start_pos_bit = 10; 
    const uint8_t stop_pos_bit = 14; 
    const uint8_t field_mask = 0x1F;

    uint8_t val_of_target = (uint8_t)((reg >> start_pos_bit) & (field_mask));

    if (val_of_target < field_mask)
    {
        val_of_target++;
        reg &= ~(field_mask << start_pos_bit); // clear bits 10 to 14
        reg |= (val_of_target << start_pos_bit);
    }

    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