21. Replace Bit Field in a 32-bit Register

Discussions1
Log in to post comments and replies.
davitkumar135
davitkumar135
Sep 05 2026

#include <stdio.h>

#include <stdint.h>

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {

    if (len == 0) {

        return reg;

    }

    uint32_t mask = (len == 32) ? 0xFFFFFFFFU : ((1U << len) - 1U);

    reg &= ~(mask << pos);

    reg |= ((val & mask) << pos);

    return reg;

}

int main() {

    uint32_t reg, val;

    uint8_t pos, len;

    if (scanf("%u %u %hhu %hhu", &reg, &val, &pos, &len) == 4) {

        printf("%u\n", replace_field(reg, val, pos, len));

    }

    return 0;

}

0