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

I want to…

Build a mask of trailing zeros

Trace this example, understand why the operation works, then try it from memory.

1 · Choose a goal → 2 · Learn the method → 3 · Practise → 4 · Spaced review

Learn the method

~x & (x − 1)8-bit word · arithmetic wraps modulo 256
BIT-BY-BIT WALKTHROUGH
OperatorBits 7 → 0Decimal
x1001 10012153
~x0110 01102102
x − 11001 10002152
Result0000 000020

x − 1 fills the trailing zeros with ones. ~x removes all positions originally set in x, so ~x & (x − 1) keeps only that trailing mask: 00000000. Odd inputs give 0; x = 0 gives all eight bits set.

IN CODEC17
#include <stdint.h>
uint8_t x = 153;

uint8_t result = (uint8_t)~x & (uint8_t)(x - 1u);

C17 · snippets use uint8_t from <stdint.h>. Casts keep the low 8 bits; shifts use unsigned operands. Run the statements inside a function.

Hacker’s Delight · §2-1

coffee-bytes / Systems LearningCS:APP + Hacker’s Delight