Two's Complement
Objectives
We would like to :
- Understand the basics of two's complement
- Perform computations in two's complement
- Understand the advantages of two's complement over sign magnitude
Notes
- This is based in part on Carpinelli
- Two's complement is a system to represent signed integers in a fixed number of bits.
- Let's look at some addition in four bits.
- 15 + 1 = 11112 + 00012 = 100002
- 14 + 2 = 11102 + 00102 = 100002
- 13 + 3 = 11012 + 00112 = 100002
- ...
- 9 + 7 = 10012 + 01112 = 100002
- There is one more, but we will ignore that for now.
- Somehow the bit patterns for 1 and 15 "complement" each other
- Or there is a sum of 00002 and a carry of 1.
- What would happen if we let the bit pattern for 15 be a -1?
- We saw that 15 + 1 = 100002
- What is 15 + 2 00102 + 11112 = 100012 1, 1
- What is 15 + 3 00112 + 11112 = 100102 1, 2
- Check up to 7, but not beyond.
- Do a few more, note the carry in and carry out for the MSB.
- What if we let the bit pattern for 14, 11102 be a -2
- Check a few, 2 through 7.
- Check the carry in and carry out to the MSB
- Check 1 (1 + -2) = 00012 + 11102 = 011112
- Is there a problem here?
- Check the carry in and carry out to the MSB
- Try -1 + -2 (11112 + 11102)
- This is 13, but following the pattern what would 13 be in our representation?
- Check the carry in and carry out to the MSB
- We have just "discovered" two's complement.
- In a n bit system, if the MSB is 0, the number is positive.
- 000...02 is 0
- 000...012 is 1
- If the MSB is 1, the number is negative.
- But what number?
- The clue comes from where we started
- 1+15 or 0001 and 1111
- 2+14 or 0010 and 1110
- 3+13 or 0011 and 1101
- It is a little hard to see but these bit patterns are one off
- 1 = 0001 -> 1110 +1 = 1111
- 2 = 0010 -> 1101 +1 = 1110
- 3 = 0011 -> 1100 +1 = 1101
- Representation an integer in two's complement
- To represent a n-1 bit positive number, just represent it in binary.
- To represent a n-1 bit negative number,
- Represent the magnitude in binary
- "flip" the bits
- Add 1.
- Let's try a few numbers in 5 bits.
- 6 is 001102 so -6 => 110012+1 = 110102
- What is -6 + 10, -6 + 2?
- 14 is 011102 so -14 => 100012+1 = 100102
- Add -14 + 15, -14 + 7
- To convert from two's complement to sign magnitude
- If the MSB is a 0 stop
- Otherwise flip the bits and add 1, represent the sign as -
- There is one strange number, in four bits 10002
- 10002=> 0111+1 -> 10002
- But try adding 1, 2, 3 .. 7
- This is -2n-1 where n is the number of bits.
- Benefits of two's complement
- Subtraction is addition
- Overflow detection, if cin ≠ cout of the MSB.
- One representation for 0
- Simple sign test, simple conversion to/from sign magnitude
- In n bits, -2n-1 to 2n-1-1 can be represented.