Embedded Systems & Firmware

In C, which statement sets only bit 3 of register reg to 1 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" is 00001000 in binary, a value (mask) with only bit 3 set. ORing (|) it with the register value forces bit 3 to 1 and leaves the other bits as they were. A plain assignment (=) would overwrite the other bits with 0 and break other peripheral settings. Bits are numbered from 0 at the least significant end.

  • A. Correct. OR sets just that bit.
  • B. All other bits would become 0.
  • C. AND would clear every bit except bit 3.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

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