All submissions

Replace Bit Field in a 32-bit Register

Code

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

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    uint32_t ones = (len == 32) ? 0xFFFFFFFF : (1U << len) - 1;
    uint32_t mask = ones << pos;
    return (reg & ~mask) | ((val << pos) & mask);
}

int main() {
    uint32_t reg, val;
    uint8_t pos, len;
    scanf("%u %u %hhu %hhu", &reg, &val, &pos, &len);
    printf("%u", replace_field(reg, val, pos, len));
    return 0;
}

Solving Approach

## Code Explanation: replace_field Function

 

This C code provides a function, replace_field, designed to replace a specific segment of bits within a 32-bit unsigned integer (uint32_t) with a new value. This is a common requirement in low-level programming, such as when interacting with hardware registers.

The core strategy is a two-step process:

  1. Clear the target bit field in the original number.
  2. Set the cleared field with the new value.

 

Loading...

Input

255 0 4 4

Expected Output

15