Extract a Bit Field from a 32-bit Register

Code

#include <stdio.h>
#include <stdint.h>
uint32_t extract_field(uint32_t reg, uint8_t pos, uint8_t len) {
    // BƯỚC 1: Dịch phải để đưa vùng bit quan tâm về vị trí 0 (LSB)
    uint32_t value = reg >> pos;

    // BƯỚC 2: Tạo mặt nạ (Mask) động dựa theo len
    // Công thức tạo mask cho 'n' bit 1 là: (1 << n) - 1
    // Ví dụ: len = 3
    // 1 << 3 = 8 (binary 1000)
    // 8 - 1  = 7 (binary 0111) -> Đúng là 3 bit 1
    uint32_t mask = (1 << len) - 1;

    // BƯỚC 3: Lọc lấy giá trị
    return value & mask;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

3060793344 28 4

Expected Output

11