Extract and Modify Field in a 32-bit Register

Code

#include <stdio.h>
#include <stdint.h>
#define LEN 5
#define MASK ((1U<<LEN)-1)
#define MAX_VAL 31
#define POS 10
uint32_t update_register(uint32_t reg) {
    // Your logic here
    //start from 10.th bit for 5 bit field
    uint32_t current_val = (reg>>POS) & MASK;
    uint32_t new_val = 0;
    if (current_val < MAX_VAL){
        new_val = current_val +1;
        reg &= ~(MASK<<POS);
        reg |= ((new_val & MASK)<<POS);
    }
    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