Bitwise Operators
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.
The shortcut
Write the numbers in binary and line up the columns. Then each operator is a column-by-column rule you can do in your head.
Write it in binary
5 is
101: DOUBLE_SCORE and SHIELD are on, MAGNET (010) is off.
Drills
Answer fast — trust the rule.
What is 6 & 3?
What is 5 ^ 1?
What is 1u << 3?
Which statement turns MAGNET off and leaves every other power-up unchanged?
If powers is 0b0101, is DOUBLE_SCORE (4) on?
Remember
- Each bit is a switch: OR turns on, AND tests, XOR toggles,
~flips all. - Shortcut: write the numbers in binary and work column by column.
- Trap:
&is not&&; bitwise operators work on bits and never short-circuit.
