Embedded Systems & Firmware

In C, which statement clears only bit 3 of register reg to 0 without changing the other bits?

  1. Areg &= ~(1 << 3);
  2. Breg |= ~(1 << 3);
  3. Creg &= (1 << 3);
Show answer and explanation

Answer: A. reg &= ~(1 << 3);

"~(1 << 3)" has only bit 3 clear and every other bit set. ANDing (&) with it forces bit 3 to 0, and the other bits, ANDed with 1, stay unchanged. OR to set, AND NOT to clear, XOR (^) to toggle and AND to test are the four basic patterns for manipulating registers in firmware.

  • A. Correct. AND with a mask that has only bit 3 clear.
  • B. OR would set every bit except bit 3.
  • C. This would clear every bit except bit 3.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. To toggle an LED output pin bit between on and off each time the code runs, which C statement is correct?
  2. Which C condition correctly tests whether bit 5 of input register in is 1?
  3. The code above rewrites a multi-bit field of register reg. What does it do?
  4. 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?
  5. 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?