#include <stdio.h>
#include <stdint.h>
unsigned int extractBitField(uint32_t reg, int pos, int len) {
unsigned int mask = (1U << len) - 1;
return (reg >> pos) & mask;
}
int main() {
uint32_t reg;
int pos, len;
// Input: 32-bit reg, position, length
scanf("%u %d %d", ®, &pos, &len);
// Output the extracted bit field
printf("%u\n", extractBitField(reg, pos, len));
return 0;
}
Right Shift reg by pos bits
This moves the desired bit field to the least significant bits.
reg >> pos
Mask only the lower len bits using:
mask = (1U << len) - 1
Bitwise AND the shifted value with the mask:
result = (reg >> pos) & mask;
Input
3060793344 28 4
Expected Output
11