#include <stdio.h>
#include <stdint.h>
uint8_t extract_field(uint16_t reg) {
return (reg >> 4) & 0x1F; // Shift right to align bits 4–8 to LSB, mask 5 bits
}
int main() {
uint16_t reg;
scanf("%hx", ®); // Hexadecimal input
printf("%u", extract_field(reg));
return 0;
}
Why is this useful in firmware?
Registers often store multiple fields like:
- Bits 0–2: mode
- Bits 4–8: prescaler
- Bits 10–15: status code
You must extract such fields without modifying the rest.
Solution Logic
- Shift right by 4 so that bit 4 becomes bit 0
- Use & 0x1F to mask the 5 least significant bits (bit 0–4)