Embedded Systems & Firmware
In C, which statement sets only bit 3 of register reg to 1 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" 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.