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.
unsigned char num = 0b11010110; unsigned char mask = 0b00001111; unsigned char result = num & mask; // result keeps lower 4 bits of num
| Step | num (binary) | mask (binary) | Operation | Result (binary) | Result (decimal) |
|---|---|---|---|---|---|
| 1 | 11010110 | 00001111 | num & mask | 00000110 | 6 |
| 2 | N/A | N/A | Use result | 00000110 | 6 |
| Variable | Start | After AND | Final |
|---|---|---|---|
| num | 11010110 (214) | 11010110 (214) | 11010110 (214) |
| mask | 00001111 (15) | 00001111 (15) | 00001111 (15) |
| result | N/A | 00000110 (6) | 00000110 (6) |
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;