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) {
    // 1. Shift the register right so the desired field starts at bit 0
    // 2. Create a mask of 'len' bits: (1 << len) - 1
    // 3. Bitwise AND them together
    
    // Handle edge case where len is 32 to avoid undefined behavior with shift
    if (len == 32) return reg;
    if (len == 0) return 0;

    return (reg >> pos) & ((1U << len) - 1);
}

int main() {
    uint32_t reg;
    uint8_t pos, len;
    
    // Note: Use %u for uint32_t and %hhu for uint8_t
    if (scanf("%u %hhu %hhu", &reg, &pos, &len) == 3) {
        printf("%u\n", extract_field(reg, pos, len));
    }
    
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

3060793344 28 4

Expected Output

11