How computers store negative numbers

· 2 min read

#how-it-works#data

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.

How -4 becomes the byte 11111100 The Int8 value -4 splits into a sign bit of 1 and seven value bits that hold 124. Together they form the byte 11111100. value: -4 sign bit = 1 7 bits hold 124 byte: 11111100 negative: 2^7 - 4 = 124 goes into the seven value bits
Simplified: the sign bit and the seven value bits together make the stored byte.

Step by step

  1. Fix the width, here 8 bits, and give the first one to the sign.
  2. Store a positive number as usual: 4 is 00000100.
  3. For a negative number, write 2^7 minus its size into the other seven bits.
  4. For -4 that gives 124, so the byte is 11111100.
  5. 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