3.7.20 · D2Algorithm Paradigms

Visual walkthrough — Bit manipulation — XOR tricks, LSB, counting set bits

1,891 words9 min readBack to topic

Prerequisite you may want open in a second tab: Two's Complement Representation and Logarithms and Powers of Two. The parent is the topic note.


Step 1 — An integer is a row of switches

WHAT. Before any trick, agree on what an integer is. A computer stores a whole number as a fixed-length row of switches. Each switch is a bit: it is either OFF (we write ) or ON (we write ).

WHY. Every trick on this page is really "look at the switches and flip some." If you picture the number as an amount you will be lost; picture it as a row of lights and every step becomes obvious.

PICTURE. Look at the figure. Each box is one switch. The box at the far right is switch number ; moving left, switch number , then , and so on. Each switch has a place value printed under it: , , , , ...

Figure — Bit manipulation — XOR tricks, LSB, counting set bits

Reading each symbol where it sits: is the state of switch (ON, OFF); is the worth of that switch; the (a "add-up-all" sign) just says: the number equals the total worth of every switch that is ON.


Step 2 — Our running example, drawn as switches

WHAT. Fix one concrete number to carry through every step: .

WHY. A derivation with pictures needs a specimen. is small enough to draw and has its lowest ON switch above position , which will make the "lowest, not zeroth" point vivid.

PICTURE. . So switches and are ON, switches and are OFF.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits

The lowest ON switch is at position (worth ). Our whole goal: get a machine to spit out , keeping nothing else. Hold the number in your head — it is the target.


Step 3 — What does "negative" do to the switches? (two's complement)

WHAT. The trick uses . But a switch-row has no minus sign — so what does the machine physically store for ? The rule is two's complement:

WHY THIS TOOL. We could ask "why not just store a sign?" Because the AND trick only works because is built by flipping and adding one — that specific recipe is what lines up a single under the lowest set bit. So we must watch the recipe act on the switches, not treat as an abstract negative.

PICTURE. Two sub-actions, drawn as two rows.

  • : flip every switch of .
  • : add one to .
Figure — Bit manipulation — XOR tricks, LSB, counting set bits

Term by term across the figure: the top row is ; the middle row is flip-all (), where every ON became OFF and vice-versa; the bottom row is add one, which we examine microscopically next because the "add 1" is where the magic hides.


Step 4 — Zoom in on the "+1": why the trailing zeros survive

WHAT. Watch the "" ripple, digit by digit, on .

WHY. This single ripple is the entire reason the answer is the lowest bit and not some other one. If you understand this ripple you understand the trick.

PICTURE. Adding starts at the rightmost switch and carries left through every ON switch until it hits the first OFF one, which it turns ON — then it stops.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits

Trace it on the figure:

  • Position : , write carry .
  • Position : , write carry .
  • Position : , write , carry stops.
  • Position : unchanged .

The key observation (green arrow in the figure): the carry marches through the region that in the original was "the lowest followed by trailing s," and it plants exactly one at position — the same place as 's lowest set bit.


Step 5 — The general picture (any number, split into three zones)

WHAT. Now do it for a general , not just , by splitting the switch-row into three zones around the lowest ON switch at position .

WHY. One example is not a proof. If we name the three zones we can watch all of , , and at once and see the pattern must always hold.

PICTURE. Write as: Here is whatever the high switches are (we don't care what), the lone is the lowest set bit, and below it sit zeros.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits

Now build in the same three zones (read straight off the figure):

zone (flip) ripple result
high untouched
pos carry lands here →
trailing all flip back to

So: where means " with every switch flipped." Notice: and agree at position (both ) and in the trailing zone (both ), but they are exact opposites in the high zone.


Step 6 — AND the two rows: everything cancels but one bit

WHAT. Apply & (AND: output only when both inputs are ) to and , zone by zone.

WHY THIS OPERATOR. We want to keep the position where both agree on and kill everywhere else. AND is precisely the "survives only if both are ON" filter — no other single operator does that.

PICTURE. Line over and AND each column.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits

Every high column dies (a switch and its flip can't both be ON). The trailing columns die (both OFF). Only column survives, holding a single . Therefore — exactly the isolated lowest set bit. For our specimen, . Target hit. ✓


Step 7 — The degenerate cases (never leave the reader stranded)

WHAT. Check the inputs that break naive intuition: , a power of two, and the all-ones number.

WHY. A trick you only tested on is a trap. We must know what happens at the edges.

PICTURE. Three tiny switch-rows.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits
  • (no switch ON). Then , and . There is no lowest set bit, and the trick correctly returns . Not a crash — a meaningful "nothing here."
  • (a power of two — a single ON switch). The lowest set bit is the only set bit, so x & -x returns itself. Consistent with the "power of two has one bit" test.
  • (lowest ON at position ). Then , trailing zone is empty, and x & -x . The formula with still holds.

The one-picture summary

This single figure compresses all seven steps: the three zones of , the flip-and-add-one that builds , and the AND that leaves one lonely bit.

Figure — Bit manipulation — XOR tricks, LSB, counting set bits
Recall Feynman retelling — explain the whole walkthrough to a 12-year-old

Picture a row of light switches; the number is just which ones are ON. To make the number "negative," the computer flips every switch and then adds one — and adding one is like a domino: it knocks over all the ON switches at the right end until it reaches the first OFF switch, which it turns ON, and then it stops. Because of that domino, the negative version matches the original at exactly one spot: the lowest switch that was ON. Everywhere else, one row's switch is ON while the other is OFF — they disagree. Now play a game called AND: keep a switch only if it's ON in both rows. Everywhere they disagreed, that switch dies. Only the one spot where they agreed lives — the lowest ON switch. So x & -x is a flashlight that always finds the rightmost light that's on, and hands you just that one, worth .

Connections

  • Two's Complement Representation — the flip-and-add-one recipe used in Steps 3–4.
  • Logarithms and Powers of Two — the highest set bit is , contrast to Step 7.
  • Hash Sets vs O(1)-space tricks — why bit tricks buy space.
  • Bitmask Dynamic Programming — iterating subsets uses x & -x.
  • Greedy and Divide-and-Conquer (Algorithm Paradigms).