Embedded Systems & Firmware
Which C condition correctly tests whether bit 5 of input register in is 1?
- Aif (in | (1 << 5))
- Bif (in == 5)
- Cif (in & (1 << 5))
Show answer and explanation
Answer: C. if (in & (1 << 5))
"in & (1 << 5)" clears every bit except bit 5, giving 32 (non-zero, true) if bit 5 is 1 and 0 (false) otherwise. In C any non-zero value is true, so it works directly as an if condition. To get exactly 1 or 0, write "(in >> 5) & 1". OR always yields a non-zero result, so it tests nothing.
- A. The OR result is never zero, so it is always true.
- B. This checks whether the value is 5, unrelated to bit 5.
- C. Correct. It masks off everything except bit 5.