Learn the method
x & ~(x + 1)8-bit word · arithmetic wraps modulo 256| Operator | Bits 7 → 0 | Decimal |
|---|---|---|
x | 1001 10012 | 153 |
x + 1 | 1001 10102 | 154 |
~(x + 1) | 0110 01012 | 101 |
Result | 0000 00012 | 1 |
Adding one clears the trailing ones; complementing sets those positions again and inverts the unchanged higher bits. AND with x cancels the higher bits, giving x & ~(x + 1) = 00000001. Even inputs give 0; the all-ones word gives 255.
#include <stdint.h>
uint8_t x = 153;
uint8_t result = 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