Bitwise Operators
The greenhouse board reports its state in one byte: is the fan on, is the heater on, is the door open, did the sensor fail? Four yes-or-no facts fit in four bits of a single integer, and on a board with a few kilobytes of memory that matters. Bitwise operators are how you read and change one bit without disturbing the others.
The rule
OR sets, AND tests, AND-NOT clears, XOR flips.
The operators work on each bit position separately. With 6 (binary 110) and 3 (binary 011):
&(AND) gives 1 only where both bits are 1:6 & 3is 2 (010).|(OR) gives 1 where either bit is 1:6 | 3is 7 (111).^(XOR) gives 1 where the bits differ:6 ^ 3is 5 (101).~(NOT) flips every bit:~0uis all ones.<<and>>shift bits left or right:1u << 3is 8 (1000).
Give each flag its own bit, and use unsigned types for bit work:
#include <stdint.h>
#define FAN_ON (1u << 0) /* bit 0: value 1 */
#define HEATER_ON (1u << 1) /* bit 1: value 2 */
#define DOOR_OPEN (1u << 2) /* bit 2: value 4 */
#define SENSOR_ERR (1u << 3) /* bit 3: value 8 */
uint8_t status = 0;
status |= HEATER_ON; /* set: heater on */
if (status & DOOR_OPEN) { } /* test: nonzero if open */
status &= ~HEATER_ON; /* clear: heater off */
status ^= FAN_ON; /* flip: toggle the fan */Rules for shifts:
x << non an unsigned value multiplies by 2 to the power n, as long as no bits fall off the top.- Shifting by a negative amount, or by at least the width of the (promoted) type, is undefined behaviour.
- Left-shifting a negative signed value is undefined; right-shifting one gives an implementation-defined result. That is another reason to keep flags unsigned.
The shortcut
Match the verb to the operator: set → OR, test → AND, clear → AND with NOT, flip → XOR. Then work one bit column at a time.
Start
statusis 0000: everything off.
Two traps. First, & is not &&: 2 & 4 is 0 while 2 && 4 is 1. Second, == binds tighter than &, so status & DOOR_OPEN == DOOR_OPEN means status & (DOOR_OPEN == DOOR_OPEN), which is status & 1. Always put parentheses around a bitwise test.
Drills
Answer fast — trust the rule.
What is 6 & 3?
What is 6 ^ 3?
What is 1u << 4?
Which line turns the heater off and leaves every other flag as it was?
With status equal to DOOR_OPEN alone (4), what is status & DOOR_OPEN == DOOR_OPEN?
Remember
- OR sets, AND tests, AND-NOT clears, XOR flips.
- Shortcut: match the verb to the operator, then work one bit column at a time.
- Trap:
&is not&&,==binds tighter than&, and flags belong in unsigned types.
