EMZETT.
Login

Two’s complement: How computers store negative numbers

In short: In two’s complement a negative number is formed by inverting all bits and adding 1; this way addition and subtraction work with the same arithmetic unit.

In more detail: Computers know only bits. For signed integers (int) practically all systems use two’s complement. It has only one zero, and addition works without special cases.

In Depth

Rule and example (8 bits)

Negate: invert all bits and add 1.

+5  =  0000 0101
inverted   = 1111 1010
+1         = 1111 1011   →  -5

The most significant bit (MSB) is the sign bit (0 = positive, 1 = negative). Range with n bits: −2^(n−1) to 2^(n−1) − 1, so with 8 bits −128 to +127, with 16 bits −32,768 to 32,767, with 32 bits −2,147,483,648 to 2,147,483,647.

Reading a number

If the MSB is 1, the number is negative: invert bits, add 1, read the result with a minus. 1111 1011 → inverted 0000 0100 → +1 = 0000 0101 = 5 → so −5. Alternatively: the MSB has the negative weight −128: 1111 1011 = −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5.

Calculating

Subtraction is addition of the negated number: 7 − 5 = 7 + (−5):

 0000 0111  (+7)
+1111 1011  (-5)
=1 0000 0010 → carry is discarded → 0000 0010 = +2

The same adder suffices, which is why CPUs use it. Overflow: if the result does not fit the range (127 + 1 = −128 in 8 bits) the sign flips: a typical error (integer overflow) that occurs in security vulnerabilities and games (counter jumps to negative).

Comparison and notes

  • Sign-magnitude (one sign bit + magnitude): two zeros (+0, −0), more complicated calculation.
  • One’s complement: only invert; also two zeros.
  • Two’s complement: one zero, simple arithmetic: standard.
  • Unsigned (no sign): 0 to 2^n − 1.
  • Floating-point numbers (IEEE 754) use another format (sign, exponent, mantissa). In the exam: proceed step by step invert, +1 and mind the range. Python has arbitrarily large int, C/Java/C# fixed widths (int32, long).

See also: Binary, decimal, hexadecimal, Bit masks, Floating-point number