Embedded Systems & Firmware

The code above rewrites a multi-bit field of register reg. What does it do?

reg = (reg & ~(0x7 << 4)) | (5 << 4);
  1. AIt sets only bit 5
  2. BIt clears the 3-bit field in bits 4-6 and then writes 5 (binary 101) into it
  3. CIt multiplies reg by 5 and shifts it left 4 bits
Show answer and explanation

Answer: B. It clears the 3-bit field in bits 4-6 and then writes 5 (binary 101) into it

0x7 is 111 in binary, so "0x7 << 4" is a mask with bits 4-6 set. ANDing with its inverse clears the field, and ORing with "5 << 4" (101 in bits 4-6) sets the field to 5 while leaving other bits unchanged. This is the standard pattern for updating registers where several bits together encode one setting, such as an operating mode or divider ratio.

  • A. It sets several bits at once.
  • B. Correct. It clears the field and then inserts the new value.
  • C. It is bit manipulation, not multiplication.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. 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?
  2. 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?
  3. When using a microcontroller GPIO (general-purpose input/output) pin, what must be configured first?
  4. 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?
  5. Which is the most suitable way to remove switch bounce in software?