Extract and Modify Field in a 32-bit Register

Code

// In embedded systems, a 32-bit configuration register often contains several packed fields. 
// Your task is to extract a 5-bit field located at bit positions 
// 10 to 14 from a 32-bit register value. 
// If this field’s value is less than 31, increment it by 1. 
// Then write the updated value back to the same bit positions in the register,
// leaving all other bits unchanged.
// Use only bitwise operations to extract, modify, and update the register.
#include <stdio.h>
#include <stdint.h>

uint32_t update_register(uint32_t reg){
    uint32_t u5tmp = (reg >> 10) & 0x1F; 
    if( u5tmp < 31){
        u5tmp++; 
        reg &= ~(0x1F << 10); 
        reg |= (u5tmp << 10);
        return reg;
    }
    return reg;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

15360

Expected Output

16384