Replace Bit Field in a 32-bit Register

Code

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


/*
* Đề bài là thay đổi một số bit bắt đầu từ vị trí `pos` bằng `val`
    1. Clear tất cả các bit từ [pos, pos + len].
    2. Set bit

    ((1 << pos) - 1) => (1 << 4) - 1 = 10 000 - 1 = 1111
    => reg & (1111) = 0b 0000 reg[3:0]

Thao tác clear các bit từ [pos, pos + len):
	reg & ~((1 << len) - 1) << pos;

Tạo bit mask với độ dài là len:
	val & ((1 << len) - 1) << pos;
*/
uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Your code here
    for (uint8_t i = pos; i < pos + len; ++i) {
        reg &= ~(1 << i);
    }

    return reg | (val << pos);
}

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

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15