How computers store negative numbers
A computer has no minus sign, only bits, so a signed integer spends its first bit on the sign. The idea to keep: a negative number is stored as 128 minus its size in the other seven bits (here for 8 bits), which is called two's complement.
The short version
Take Int8, a signed 8-bit integer. The first bit is the sign: 0 for positive, 1 for negative. A positive number is stored exactly as in an unsigned integer. A negative number puts 2^7 minus its size into the seven bits that remain. Because of that layout, signed numbers add with ordinary binary addition. The table shows the same eight bits read both ways.
Step by step
- Fix the width, here 8 bits, and give the first one to the sign.
- Store a positive number as usual: 4 is 00000100.
- For a negative number, write 2^7 minus its size into the other seven bits.
- For -4 that gives 124, so the byte is 11111100.
- Add -1 and -4 with plain binary addition and discard the bit that does not fit. The answer is correct.
| UInt8 | Int8 | |
|---|---|---|
| Smallest value | 0 | -128 |
| Largest value | 255 | 127 |
| 11111100 reads as | 252 | -4 |
Why it matters
The upside is that the CPU needs no special case for negatives, since addition works the same way. The downside is a lopsided range with one more negative value than positive, and overflow: Swift's + reports an error, while &+ and &- wrap around, so Int8.min &- 1 lands on the largest value.
Sources
- The Swift Programming Language, Advanced Operators: the first bit is the sign, positives match unsigned, a negative stores 2^7 minus its size (-4 is 11111100), plain binary addition drops bits that do not fit,
+reports overflow and&+/&-wrap - The Swift Programming Language, The Basics: UInt8 runs from 0 to 255, Int8 from -128 to 127
- The Rust Reference, Numeric types: signed integer types are two's complement, i8 spans -(2^7) to 2^7-1