How to Extract Bits from Register in Embedded C
To extract bits from a register in Embedded C, use bitwise AND
& with a mask to isolate the bits, then right-shift >> if needed to align them. For example, (register & mask) >> shift extracts the desired bits cleanly.Syntax
Use the bitwise AND operator & with a mask to select bits, then right-shift >> to move them to the least significant bit position.
register: The variable holding the bits (usually a hardware register).mask: A binary value with 1s in the bit positions you want to extract.shift: Number of bits to move right to align extracted bits to bit 0.
c
extracted_bits = (register & mask) >> shift;
Example
This example shows how to extract bits 4 to 6 from an 8-bit register variable.
c
#include <stdio.h> int main() { unsigned char reg = 0b10110110; // Example register value unsigned char mask = 0b01110000; // Mask for bits 4,5,6 unsigned char shift = 4; // Shift right by 4 to align bits unsigned char extracted = (reg & mask) >> shift; printf("Register value: 0x%02X\n", reg); printf("Extracted bits (4-6): 0x%X\n", extracted); return 0; }
Output
Register value: 0xB6
Extracted bits (4-6): 5
Common Pitfalls
Common mistakes when extracting bits include:
- Using the wrong mask that includes unwanted bits.
- Forgetting to shift the bits right after masking, resulting in incorrect values.
- Using signed types which can cause unexpected sign extension during shifts.
Always use unsigned types and carefully define masks.
c
/* Wrong way: No shift after masking */ unsigned char wrong = reg & mask; // bits not aligned /* Right way: Mask then shift */ unsigned char right = (reg & mask) >> shift;
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Masking | Select bits using AND with mask | value & 0x0F |
| Shifting Right | Align bits to LSB | (value & 0xF0) >> 4 |
| Shifting Left | Move bits left (less common for extraction) | value << 2 |
Key Takeaways
Use bitwise AND with a mask to isolate desired bits from a register.
Right-shift the masked bits to align them to the least significant bit position.
Always use unsigned types to avoid sign extension issues during shifts.
Define masks carefully to include only the bits you want to extract.
Test your bit extraction with known register values to verify correctness.