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

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint32_t update_register(uint32_t reg) {
    // Your logic here
    uint32_t mask = 0x1F;
    uint8_t tmp = (reg >> 10) & mask;
    if (tmp < 31) {
        tmp += 1;
        reg &= ~(mask << 10);
        reg |= (tmp << 10);
    }
    return reg;
}

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

Solving Approach

Extract the field bits using a bitmask and left shifting the 10-14 bits to the LSB.

Check the extracted value in tmp for the condition less than 31. Increment accordingly.

CLear the bits 10-14 and replace them with the tmp value.

 

 

Was this helpful?
Upvote
Downvote