All submissions

Extract and Modify Field in a 32-bit Register

Code

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

uint32_t update_register(uint32_t reg) {
    // Your logic here
    const uint32_t FIELD_START_BIT = 10;
    const uint32_t FIELD_WIDTH = 5;
    const uint32_t MAX_FIELD_VALUE = 31;
    const uint32_t FIELD_MASK = ((1U << FIELD_WIDTH) - 1U) << FIELD_START_BIT;
  uint32_t extracted_value = (reg & FIELD_MASK) >> FIELD_START_BIT;
  // 4. Modify the extracted value based on the condition.
    uint32_t new_value = extracted_value;
    if (extracted_value < MAX_FIELD_VALUE) {
        new_value = extracted_value + 1;
    }
// Prepare the new value for re-insertion.
    // Left shift the new value back to its original bit positions.
    uint32_t new_value_shifted = new_value << FIELD_START_BIT;

    // 6. Update the register.
    // First, clear the existing field in the register using an inverse mask (~).
    // Then, use bitwise OR to insert the new, shifted value.
    uint32_t updated_reg = (reg & ~FIELD_MASK) | new_value_shifted;

    return updated_reg;
}
    

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

Solving Approach

 

 

 

Loading...

Input

15360

Expected Output

16384