#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", ®, &val, &pos, &len);
printf("%u", replace_field(reg, val, pos, len));
return 0;
}
## 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:
Input
255 0 4 4
Expected Output
15