SYSTEMS / Learn
Saved on this device>
← Back to goals

I want to…

Negate a fixed-width word

Trace this example, understand why the operation works, then try it from memory.

1 · Choose a goal → 2 · Learn the method → 3 · Practise → 4 · Spaced review

Learn the method

−x ≡ ~x + 1 (mod 256)8-bit word · arithmetic wraps modulo 256
BIT-BY-BIT WALKTHROUGH
OperatorBits 7 → 0Decimal
x1001 10012153
~x0110 01102102
Result0110 01112103

The negated word is 01100111. Word negation wraps modulo 256, including the special patterns 00000000 and 10000000.

IN CODEC17
#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

coffee-bytes / Systems LearningCS:APP + Hacker’s Delight