Home / Learn Embedded C / Extracting a Multi-Bit Field from a Register
Extracting a Multi-Bit Field from a Register
Pulling out a specific group of bits (like a 3-bit "channel" field) as its own number.
Breaking it down
The basic idea
Extracting a multi-bit field means isolating a specific range of bits and shifting them down to start at bit 0, turning them into an ordinary, directly-usable number.
Why this comes up
A register field like a 3-bit "ADC channel selector" or a 2-bit "baud rate divisor" needs to be read out as a clean 0-7 or 0-3 number, not left shifted up in the middle of a byte.
The mechanics
The pattern is: (register & field_mask) >> field_position — mask out everything except the field, then shift it down so it starts at bit 0, exactly the inverse of how a field is written (shift up, then mask, then OR in).
Where it is used
- ADC channel selection
- Baud rate/prescaler fields
- Any multi-bit register field
Try it
The result, 5, is a clean, directly-usable number — exactly as if it had been stored starting at bit 0.
Try it: extracting two different fields from one register
A single register byte can hold several independent fields side by side — each is extracted with its own mask-then-shift pair.
Quick check
1. What is the correct order of operations to extract a shifted-up field cleanly as a 0-based number?
Masking first isolates the field's bits (leaving other bits as 0); shifting down then brings that field to start at bit 0 as a clean number.