Learn the method
−x ≡ ~x + 1 (mod 256)8-bit word · arithmetic wraps modulo 256| Operator | Bits 7 → 0 | Decimal |
|---|---|---|
x | 1001 10012 | 153 |
~x | 0110 01102 | 102 |
Result | 0110 01112 | 103 |
The negated word is 01100111. Word negation wraps modulo 256, including the special patterns 00000000 and 10000000.
#include <stdint.h>
uint8_t x = 153;
uint8_t result = (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.
CS:APP · §2.2.3, §2.2.7, §2.3.3