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) {
    // If nothing to replace or position out of range, return original register
    if (len == 0 || pos >= 32) {
        return reg;
    }

    // Cap len so pos + len doesn't exceed 32 (avoid undefined shifts)
    if ((uint16_t)pos + (uint16_t)len > 32) {
        len = 32 - pos;
    }

    // Build a mask of 'len' ones, aligned to 'pos'.
    // Use 64-bit during construction to avoid undefined behavior when len is large.
    uint64_t ones = (len == 32) ? 0xFFFFFFFFull : ((1ull << len) - 1ull);
    uint64_t mask64 = ones << pos;
    uint32_t mask = (uint32_t)mask64;

    // Place only the lower 'len' bits of val into position and mask them
    uint32_t placed = ((uint32_t)val << pos) & mask;

    // Clear target bits in reg, then OR in the placed value
    return (reg & ~mask) | placed;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15