_TOP_MENU

Jul 1, 2016

Two's Complement

The two's complement of an N-bit number is defined as the complement with respect to 2N; in other words, it is the result of subtracting the number from 2N



Three-bit two's-complement integers
Bits Unsigned
value
Two's
complement
value
011 3  3 
010 2  2 
001 1  1 
000 0  0 
111 7  -1 
110 6  -2 
101 5  -3 
100 4  -4


Eight-bit two's-complement integers
Bits Unsigned
value
Two's
complement
value
0111 1111 127  127 
0111 1110 126  126 
0000 0010 2  2 
0000 0001 1  1 
0000 0000 0  0 
1111 1111 255  −1 
1111 1110 254  −2 
1000 0010 130  −126 
1000 0001 129  −127 
1000 0000 128  −128 


The term two's complement can mean either a number format or a mathematical operator. For example, 0111 represents decimal 7 in two's-complement notation, but the two's complement of 7 in a 4-bit register is actually the "1001" bit string (the same as represents 9 = 24 − 7 in unsigned arithmetics) which is the two's complement representation of −7. The statement "convert x to two's complement" may be ambiguous, since it could describe either the process of representing x in two's-complement notation without changing its value, or the calculation of the two's complement, which is the arithmetic negative of x if two's complement representation is used.

Converting to two's complement representation

Invert all bits and add 1.

Example

1.
+ 15   ->  0000 1111
+  5   ->   0000 0101
------       --------------------
  20          0001 0100

2.

+ 15  ->   0000 1111       ->    0000 1111
-  5    -> -  0000 0101  2's ->   1111 1011 
                                              --------------------
                                             1 0000 1010  -> 10 , ignore Carry

3.
- 15   ->   -  0000 1111  2's  ->  1111 0001
+  5  ->      0000 0101         ->  0000 0101
                                                -------------------
                                                 1111 0110   ->  sign bit is 1 , take 2's complement
                  2's ->   0000 1010   -> -10 (Answer)

4.
- 15  ->   - 0000 1111   2's ->  1111 0001
-  5   ->   - 0000 0101   2's ->  1111 1011
                                               --------------------
                                             1 1110 1100  -> Ignore Carry ,Sign bit is 1 , take 2's complement
             1110 1100   -> 2's ->  0001 0100  ->  -20 (Answer)       


No comments:

Post a Comment