Extract and Modify Field in a 32-bit Register

Code

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

#define BITS_LEN 	5
#define START_BIT	10

uint32_t update_register(uint32_t reg) {
	// create a mask
	uint32_t mask = ((1 << BITS_LEN) - 1) << START_BIT;
	// extract bits
	uint32_t extract_bits = reg & mask;
	uint32_t specific_bits = (extract_bits >> START_BIT);
	// check if the extracted bits are <31 then increment by 1
	if(specific_bits< 31){
		specific_bits += 1;
	}
	// replace those targeted field into the reg
	reg &= ~mask;

	reg |= specific_bits << START_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