Two’s Complement

In many computer science related fields, you are going to encounter or require the knowledge of Two’s complement.

Two’s complement is a way of representing negative numbers in binary.

Two’s complement is the way every computer chooses to represent integers.

Implementation

For example, let’s use an 8 bit long binary number:

0   0   0   0   0   0   0   0 | 8 bit long
128 64  32  16  8   4   2   1 | Value Represented
0   0   0   1   0   1   0   0 | Number chosen is 20

So the 8 bit number we chose is equivalent to 20 in decimal format. But what if we are looking for the negative counterpart; -20?

To find -20 in binary form, the most convenient way is as follows:

First you find the least significant bit- the smallest non-zero bit, which is 100 of binary (equivalent to 4 in decimal). You keep the 100 of binary as is, but the values of the rest of the bits to the left is flipped. Like so:

1   1   1   0   1   1   0   0 | This is Two's Complement for -20

Binary Addition with Two’s Complement

The great thing about Two’s Complement is that math works the same way when you are adding and subtracting numbers in binary; whether they are in Two’s Complement or not. So to become familiar with how to do binary addition with Two’s Complement, let’s evaluate 24 + (-20).

    0   0   0   1   1   0   0   0 | Number chosen is 24
+   1   1   1   0   1   1   0   0 | Two's Complement -20
----------------------------------
1   0   0   0   0   0   1   0   0 | We are working with 8 bits, so drop the first 1 

    0   0   0   0   0   1   0   0 | equivalent to 4

But there is a caveat! The number 1 at the far left of the resulting number is dropped or doesn’t count! That’s because we are working with Two’s Complement or 8 bit numbers, not 9 bits. The result you get is 00000100, which is equivalent to 4.

 

What's Your Opinion?