SYSTEMS / Learn
Saved on this device>
← Back to curriculum

Learning-oriented

Work from the rightmost bit

Choose an idiom by its goal: clear, set, isolate, or build a trailing-bit mask.

1 · Understand → 2 · Explain from memory → 3 · Practise → 4 · Spaced review

Subtracting one clears the rightmost 1 and turns the zeros below it into ones. AND with the original word keeps those lower positions zero: x & (x − 1) clears exactly the rightmost set bit. At x = 0 the result remains zero.

Adding one sets the rightmost 0 and clears the trailing ones below it. OR with the original restores those ones: x | (x + 1) sets the rightmost zero bit. Using AND instead, x & (x + 1), clears the trailing run of ones. Similarly, x | (x − 1) sets the trailing run of zeros.

To isolate rather than modify, use x & (−x) for the rightmost 1 or ~x & (x + 1) for the rightmost 0. The formulas x & ~(x + 1) and ~x & (x − 1) build masks of trailing ones and trailing zeros. These are fixed-width unsigned identities: use explicit wrapping addition and subtraction in Zig and Rust, and unsigned arithmetic with an 8-bit cast in C.

Explain it before you practise

Look away from the example. Explain why it works and predict a boundary case. Then check your reasoning.

Explain the difference between x & (x − 1) and x & (−x). What does each return for x = 0?

Check your reasoning

The first clears the rightmost 1 and preserves the other set bits. The second isolates that 1 and clears everything else. Both return zero for zero input under fixed-width unsigned arithmetic.

Cement this knowledge

Solve ten fresh questions without the worked example. Mistakes return during the session; spaced review helps you recall the method on later days.

Practice this topic →
coffee-bytes / Systems LearningCS:APP + Hacker’s Delight