SlightlyLoony
Tera Contributor

find_real_file.pngThere are times when it's very handy to understand exactly how numbers are represented inside a computer. I'm sure you know that numbers (at least integers) are represented in binary (base 2) form. But do you know how negative numbers are represented inside a computer?

Virtually all modern computers use a system called "two's complement" to represent negative numbers. The reason for choosing this method dates back to the early days of computers, when hardware was very dear: two's complement representation eliminates the need for special hardware to represent negative numbers or to subtract. With two's complement representation, you do subtraction by addition.

Two's complement only works with binary numbers, but there are equivalent representations for numbers expressed in any base, including decimal numbers (base 10). The table below shows how a complementary representation works for the same two numbers (83 - 38) subtracted in decimal (base 10), septenary (base 7), and binary (base 2).







OperationDecimalSeptenaryBinary
Minuend8314601010011
Subtrahend3805300100110
Subtrahend (Base - 1) Complement6161311011001
Subtrahend Base Complement6261411011010
Difference (Ignoring Carry)4506300101101


Above you can see all the steps needed to compute (83 - 38) in the three different bases (Difference = Minuend - Subtrahend, in math-speak). To make this computation by adding, instead of subtracting, we first need to compute the base complement of the subtrahend. For decimal numbers, that's the 10s complement; for septenary numbers that's the 7s complement, and for binary numbers that's the 2s complement. Then if you add the minuend and the subtrahend base complement, you get the difference (but you have to ignore the last carry). In our example, decimal 83 (the minuend) plus 62 (the subtrahend base complement) equals 145 — but ignoring the last carry, that's just 45, which is the correct answer. We just calculated (83 - 38) by adding! The same thing works with the other bases.

But how do you come up with the subtrahend base complement? It turns out that the easiest way is to calculate the subtrahend (base - 1) complement first, then add one to it to get the subtrahend base complement. For decimal, the (base - 1) complement is the 9s complement, for septenary it's the 6s complement, and for binary it's the 1s complement. To calculate the 9s complement in decimal, you replace each digit of the number with 9 minus the digit — so you replace the 3 with a 6, and the 8 with a 1. It works the same way with the other bases, but with binary numbers this turns out to be extremely simple: you just replace 1s with 0s, and 0s with 1s (you just "flip" all the bits). This latter feature is one of the things attracted the early computer designers to complementary math.

So how do computers represent negative numbers? In two's complement form, of course!