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>

#define REG_FIELD_SHIFT     10U
#define REG_FIELD_MASK      0x1FU
#define REG_FIELD_MAX_VALUE 31U

uint32_t update_register(uint32_t reg) {    
    // Your logic here
    uint32_t target_field = 0U;
    uint32_t update_reg = reg;

    target_field = (reg >> REG_FIELD_SHIFT) & (uint32_t)REG_FIELD_MASK; 

    if (REG_FIELD_MAX_VALUE > target_field){

        target_field += 1U;

        update_reg &= ~(REG_FIELD_MASK << REG_FIELD_SHIFT);
        update_reg |= (target_field << REG_FIELD_SHIFT);

    }
    return update_reg;
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote