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 |
Result | 1001 10002 | 152 |
x + 1 turns the trailing ones into zeros and sets the zero immediately above them. AND with x removes that extra set bit, leaving x & (x + 1) = 10011000. An even word is unchanged; 255 wraps to a result of 0.
#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