Bitwise Operators
Bitwise operators work on the individual bits of an integer, which makes one unsigned number a compact set of on-or-off flags.
Use bit masks to inspect, set and clear individual flags.
Rocket Run has power-ups: a shield, a coin magnet, double score. You could keep three bool variables, but game code (and file formats, network packets and hardware registers) often packs such switches into the bits of a single number. Bitwise operators are how you flip and read those switches.
The rule
Each bit is a switch: | turns on, & tests, ^ toggles, ~ flips all.
Give each power-up its own bit:
constexpr unsigned SHIELD = 1u << 0; // 0b001 = 1
constexpr unsigned MAGNET = 1u << 1; // 0b010 = 2
constexpr unsigned DOUBLE_SCORE = 1u << 2; // 0b100 = 4
unsigned powers = 0;
powers |= MAGNET; // turn on
bool hasMagnet = (powers & MAGNET) != 0; // test
powers ^= SHIELD; // toggle
powers &= ~MAGNET; // turn offThe operators, bit by bit:
a & b(AND): 1 only where both bits are 1.a | b(OR): 1 where either bit is 1.a ^ b(XOR): 1 where the bits differ.~a(NOT): flips every bit.a << nanda >> n: shift the bits left or right by n places. For unsigned values that stay in range,<< nmultiplies by 2 to the power n.
Use unsigned types for flags; shifting signed negative numbers has surprising rules. And remember that & and | are not && and ||: the single forms work on bits and never stop early.