4. The following code is intended to mask the upper 4 bits of 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);
medium
A. Mask value is incorrect
B. Missing parentheses around expression
C. Variable types are wrong
D. Using OR (|) instead of AND (&) for masking
Solution
Step 1: Understand masking operation
Masking to keep bits requires AND (&), not OR (|).
Step 2: Identify incorrect operator
The code uses OR which sets bits instead of masking.
Final Answer:
Using OR (|) instead of AND (&) for masking -> Option D
Quick Check:
Masking needs AND, not OR [OK]
Hint: Mask bits with & not | [OK]
Common Mistakes:
Using OR instead of AND
Changing mask value unnecessarily
Assuming parentheses fix bitwise errors
5. You have a 16-bit sensor data stored in 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?
hard
A. temperature = (data | 0xFF00) >> 8;
B. temperature = data & 0x00FF;
C. temperature = (data & 0xFF00) >> 8;
D. temperature = data >> 8;
Solution
Step 1: Identify mask for upper 8 bits
Upper 8 bits mask is 0xFF00 (binary 11111111 00000000).
Step 2: Apply AND and shift right
Use (data & 0xFF00) to keep upper bits, then shift right 8 to get value.
Final Answer:
temperature = (data & 0xFF00) >> 8; -> Option C
Quick Check:
Mask upper 8 bits and shift right [OK]
Hint: Mask upper bits with 0xFF00 then shift right 8 [OK]
Common Mistakes:
Masking lower bits instead
Using OR instead of AND
Forgetting to shift after masking
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.