2s Complement Better Explained

So, this did not go well last session. Let's address this:

2's Complement is 1's complement (flipping all the bits) but adding the decimal value 1 to the decimal value of the result.

Unsigned 2's Complement Binary
5 5 0000 0101
251 -5 1111 1011
1 1 0000 0001
254 -2 1111 1110
255 -1 1111 1111

-10 in 2's complement

  1. Find binary representation for 10

    0000 1010

  2. Flip all bits (1's complement)

    1111 0101

  3. Add one

    1111 0110

Examples (4 Bit Binary)

Two’s Complement Decimal Number
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 -8
1001 -7
1010 -6
1011 -5
1100 -4
1101 -3
1110 -2
1111 -1

The Sign Bit

The most significant (leftmost) bit indicates the sign of the integer; therefore it is sometimes called the sign bit.

If the sign bit is zero,
    then the number is greater than or equal to zero, or positive. 
If the sign bit is one,
    then the number is less than zero, or negative. 

Look at the example above, does that mean we can represent -10 in 4 bit binary?

What is the minimum number of bits we can represent it in?

The Sign Bit

Negative numbers are written with a leading one instead of a leading zero.

So, if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127.

"1xxxxxxx" is reserved for writing negative numbers.

A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1).

So:

  • -1 is complement(1 - 1) = complement(0) = "11111111"
  • -10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110".

This means that negative numbers go all the way down to -128 ("10000000").

Exercise

Convert the following to 2s complement using 6 bit representation

  • -16
  • 13
  • -3
  • -10
  • 26
  • -31