Learn the method
x & (−x)8-bit word · arithmetic wraps modulo 256| Operator | Bits 7 → 0 | Decimal |
|---|---|---|
x | 1001 10012 | 153 |
−x | 0110 01112 | 103 |
Result | 0000 00012 | 1 |
Negation flips every bit and adds one. The carry preserves the rightmost 1 and the zeros below it, while all higher bits are inverted. AND with x therefore keeps only that one bit: 00000001. If x is zero, the result is zero.
#include <stdint.h>
uint8_t x = 153;
uint8_t result = x & (uint8_t)(0u - x);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