Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Basic Operations  ›  Capstone Project

Bitwise Operators

Bitwise Operators 12 minBitwise operators work on the individual bits of an integer, which makes one unsigned number a compact set of on-or-off flags.

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 off

The 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 << n and a >> n: shift the bits left or right by n places. For unsigned values that stay in range, << n multiplies 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.

powers = 5, then add the magnetStep 1 of 4
  1. Write it in binary

    5 is 101: DOUBLE_SCORE and SHIELD are on, MAGNET (010) is off.

Drills

Answer fast — trust the rule.

quick drill

What is 6 & 3?

quick drill

What is 5 ^ 1?

quick drill

What is 1u << 3?

quick drill

Which statement turns MAGNET off and leaves every other power-up unchanged?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPower-up flags

Rocket Run stores power-ups in one unsigned int: SHIELD is 1, MAGNET is 2, DOUBLE_SCORE is 4. Explain how to turn MAGNET on, test whether it is on, and turn it off again, and why each operator does its job.