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 10102 | 154 |
Result | 0000 00102 | 2 |
x + 1 sets the rightmost zero and clears the trailing ones. ~x keeps positions that were originally zero, so ~x & (x + 1) isolates just the newly set bit: 00000010. For x = 255 there is no zero bit and the result is 0.
#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