Learn the method
~x & (x − 1)8-bit word · arithmetic wraps modulo 256| Operator | Bits 7 → 0 | Decimal |
|---|---|---|
x | 1001 10012 | 153 |
~x | 0110 01102 | 102 |
x − 1 | 1001 10002 | 152 |
Result | 0000 00002 | 0 |
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.
#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