Bitwise Operators
Bitwise operators work on individual bits, so a single unsigned integer can hold many on/off flags that are set with OR, tested with AND, cleared with AND-NOT and flipped with XOR.
Inspect flags with masks and shifts while keeping the integer width explicit.
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.