0
0
Embedded Cprogramming~10 mins

AND for masking bits in Embedded C - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - AND for masking bits
Start with number
Apply AND mask
Result keeps bits where mask=1
Result clears bits where mask=0
Use result as needed
End
This flow shows how applying an AND mask keeps certain bits and clears others in a number.
Execution Sample
Embedded C
unsigned char num = 0b11010110;
unsigned char mask = 0b00001111;
unsigned char result = num & mask;
// result keeps lower 4 bits of num
This code uses AND to keep only the lower 4 bits of num, clearing the upper bits.
Execution Table
Stepnum (binary)mask (binary)OperationResult (binary)Result (decimal)
11101011000001111num & mask000001106
2N/AN/AUse result000001106
💡 Finished applying AND mask; bits where mask=0 are cleared.
Variable Tracker
VariableStartAfter ANDFinal
num11010110 (214)11010110 (214)11010110 (214)
mask00001111 (15)00001111 (15)00001111 (15)
resultN/A00000110 (6)00000110 (6)
Key Moments - 2 Insights
Why does the result only keep some bits of num?
Because AND with mask keeps bits only where mask has 1s (see execution_table step 1). Bits where mask is 0 become 0 in result.
What happens if mask is all zeros?
Result will be zero because AND with 0 clears all bits (not shown here but follows same logic).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 1, what is the decimal value of the result?
A214
B6
C15
D110
💡 Hint
Check the 'Result (decimal)' column in execution_table step 1.
At which step does the AND operation happen?
AStep 1
BBefore Step 1
CStep 2
DNo AND operation
💡 Hint
Look at the 'Operation' column in execution_table.
If mask was 0b11110000 instead, what bits of num would be kept?
AAll bits
BLower 4 bits
CUpper 4 bits
DNo bits
💡 Hint
Mask bits with 1 keep those bits in num (see concept_flow).
Concept Snapshot
AND for masking bits:
- Use & operator between number and mask
- Bits where mask=1 stay same
- Bits where mask=0 become 0
- Useful to extract or clear bits
- Example: result = num & mask;
Full Transcript
This example shows how to use the AND operator to mask bits in embedded C. We start with a number and a mask. The mask has 1s where we want to keep bits and 0s where we want to clear bits. Applying AND between the number and mask keeps bits where mask is 1 and clears others. For example, num = 0b11010110 and mask = 0b00001111 results in 0b00000110, keeping only the lower 4 bits. This technique is useful to extract parts of a number or clear unwanted bits.