Saturday, June 23, 2018

Signed number representation & Importance of 2's Complement

Signed number representation :-

In any system we obviously need to represent both positive and negative numbers there are 3 methods to do such task:-

  • Sign-and-magnitude
  • 1's complement 
  • 2's complement
In all 3 methods leftmost bit is 0 for positive and 1 for negative number. If we consider 4-bit  numbers all positive numbers that can be generated are same in all 3 methods of number representation. Difference is seen in case of negative numbers, in sign-and-magnitude negative values are represented by changing the most significant bit from 0 to 1. For example +5 is 0101 and -5 is 1101. In 1's complement representation negative values are obtained by complementing each bit, for example: +3 is 0011 and -3 is 1100. 2's complement of a number is found by adding 1 to 1's complement , +7 is 0111 and -7 is 1001 (1's complement of +7 is 1000 we add 1 in it to get 2's complement).


There is a distinct representation of +0 and -0 in both sign and magnitude and 1's complement representation but 2's complement have only 1 representation of 0. For 4 bits value -8 is represented in 2's complement but not in other representations. Most natural is sign and magnitude system, 1's complement is easily related but 2's complement gives an uneasy feeling so why is it even used. Bear  for a moment as your question will be answered once and for all in following topic.

Addition and Subtraction of Signed numbers :-

The sign-and-magnitude representation is simplest of 3 but when performing addition and subtraction it is the most awkward of all. 1's complement is little better than sign-and-magnitude. But 2's complement method is best for addition and subtraction of signed numbers.
To understand 2's complement arithmetic lets consider modulo N (mod N) addition. A circle is marked form 0 to N-1 along its perimeter. In our case N=16 (4 bits).


So if our operation is (7+4) mod 16 gives value 11, to perform this graphically we locate 7 on circle and move 4 units clockwise arriving at answer 11. Lets apply mod 16 on addition of +7 and -3, when we perform binary addition of +7 and -3 in 2's complement form it will be 0111 and 1101.

   0111
+1101
---------
10100
↑        
Carry-out

By our graphical method we locate 0111 and take 1101 (13) steps clockwise we arrive at 0100 (+4) which is correct answer. If we ignore carry-out from our binary addition we get our answer. Ignoring carry out is natural result of mod N arithmetic. This ignorance of carry out is what makes 2's complement best suited for arithmetic operations.
Note that addition is only algebraically correct if answer lies in range of -2n-1 to +2n-1 - 1. In our case of 4 bits its -8 to +7.


Suggestions:-

Aneesh Dogra's post : Signed and unsigned additions in x86
Amitesh's post : Signed and unsigned numbers



No comments:

Post a Comment