Embedded Systems & Firmware
The code above rewrites a multi-bit field of register reg. What does it do?
reg = (reg & ~(0x7 << 4)) | (5 << 4);
- AIt sets only bit 5
- BIt clears the 3-bit field in bits 4-6 and then writes 5 (binary 101) into it
- 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.