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;
val in embedded C?unsigned char val = 0xAB; // 10101011 in binary
unsigned char mask = 0x0F; // 00001111 in binary
unsigned char result = val & mask;
printf("%02X", result);val, but it does not work as expected. What is the error?unsigned char val = 0xAB; // 10101011
unsigned char mask = 0xF0; // 11110000
unsigned char result = val | mask;
printf("%X", result);uint16_t data. The upper 8 bits represent temperature, and the lower 8 bits represent humidity. How do you extract only the temperature value using AND masking?Pass the test and this pattern moves unknown