Digital logic
Two's complement (signed integers)
Also called: signed binary · negative numbers in binary · integer overflow · int8
Definition
Two's complement represents negative integers so that ordinary binary addition still works: the top bit has a negative place value, so an n-bit number ranges from −2^(n−1) to 2^(n−1) − 1.
Picture it
To negate, invert every bit and add 1. In 8 bits, 1111 1111 is −1 and 1000 0000 is −128. Adding past the largest value wraps around to the most negative, which is the overflow bug behind many 'robot suddenly spins backwards' stories.
The maths
value = −b_(n−1) × 2^(n−1) + Σ_(i<n−1) b_i × 2^i −x = (NOT x) + 1
| Quantity | Unit | Symbol |
|---|---|---|
| information | bit | bit |
| ratio | dimensionless | 1 |
Worked example
What is 1111 1011 as an 8-bit signed number? What happens when an int8 holding 127 has 1 added?
- Unsigned value 251; minus 256 → −5
- Check: invert 1111 1011 → 0000 0100, add 1 → 0000 0101 = 5, so it was −5
- 127 + 1 = 0111 1111 + 1 = 1000 0000 = −128
Answer−5; 127 + 1 overflows to −128.
✓ The 2 numbers in this answer are recomputed from scratch by an automated test.
flip the bits
Binary, decimal and hex
Unsigned and two's-complement readings of the same bit pattern. Python ints are unbounded; microcontroller registers are not.
Common misconceptions
- Misconception: The top bit is not just a sign flag; it carries a weight of −128 in 8 bits.
- Misconception: Python ints never overflow, but microcontroller integers do.