Embedded Systems & Firmware
In C, which statement clears only bit 3 of register reg to 0 without changing the other bits?
- Areg &= ~(1 << 3);
- Breg |= ~(1 << 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.