·  COMMON – Two's complement

 

- Info:

  - Two's complement is a way of representing negative numbers by using N bits.

  - This tutorial is based on http://en.wikipedia.org/wiki/Two's_complement.

 

- Procedure:

  - Procedure will be explained by using N=4 bits.

  - Zero is represented by making all bits equal to zero which yields: 0000

  - For positive numbers highest bit, left most one, is 0.

  - For negative numbers highest bit, left most one, is 1.

  - Positive numbers are created simply by adding that amount to 0000.

    This means that the biggest positive number is 0111=7=24-1-1=2N-1-1.

  - Negative numbers are created by inverting bits of their absolute value and adding 1:

    -1=inv(|-1|)+1=inv(1)+1=inv(0001)+1=1110+1=1111

    -4=inv(|-4|)+1=inv(4)+1=inv(0100)+1=1011+1=1100

    -8=inv(|-8|)+1=inv(8)+1=inv(1000)+1=0111+1=1000

    -9=inv(|-9|)+1=inv(9)+1=inv(1001)+1=0110+1=0111 (can't represent -9)

  - The same procedure can be used in reverse to find which negative numbers bits represent:

    1111=inv(1111)+1=0000+1=0001=-1

    1100=inv(1100)+1=0011+1=0100=-4

    1000=inv(1000)+1=0111+1=1000=-8

  - When two such numbers need to be added they are simply added discarding overflow bit:    

    -3+5=[inv(|-3|)+1]+5=[inv(3)+1]+5=[inv(0011)+1]+0101=[1100+1]+0101=1101+0101=10010®0010=2

    -3-2=[inv(|-3|)+1]+[inv(|-2|)+1]=[inv(0011)+1]+[inv(0010)+1]=[1100+1]+[1101+1]=1101+1110=1011=-5

 

  - Two's complement for N=4:

    0111   7

    0110   6

    0101   5

    0100   4

    0011   3

    0010   2

    0001   1

    0000   0

    1111  −1

    1110  −2

    1101  −3

    1100  −4

    1011  −5

    1010  −6

    1001  −7

    1000  −8

 

- Two's complement maximum and minimum values:

  8  bits [              0x80 , 0x7F              ] [       -128 , 127       ]

  16 bits [            0x8000 , 0x7FFF            ] [     -32768 , 32767     ]

  32 bits [        0x80000000 , 0x7FFFFFFF        ] [-2147483648 , 2147483647]

  64 bits [0x8000000000000000 , 0x7FFFFFFFFFFFFFFF] [    -2^64/2 , 2^64/2-1  ]