Embedded Systems & Firmware

Which C condition correctly tests whether bit 5 of input register in is 1?

  1. Aif (in | (1 << 5))
  2. Bif (in == 5)
  3. 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.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. The code above rewrites a multi-bit field of register reg. What does it do?
  2. While the main code updates a register bit with "reg |= mask;" (read-modify-write), an interrupt handler changes a different bit of the same register. Which pairs the possible problem with a fix correctly?
  3. A switch alone is connected to a microcontroller input pin, with no pull-up or pull-down resistor. What can happen while the switch is open?
  4. When using a microcontroller GPIO (general-purpose input/output) pin, what must be configured first?
  5. What is the phenomenon called in which a mechanical switch's contacts bounce, turning on and off many times in a short period when pressed?