What:

It is a simple algorithm which is used for representing integers in computer. The input is any Binary number. And the output is the equivalent decimal number. For the example problem, We are using the 4 bit combinations only, but it works with n bit number also; where n is any positive integer. It is divided into two parts for Signed integer as positive signed and negative signed.

Why:

This algorithm works well with any n bit no without failing, as it uses Two's complement method for conversion for Negative signed integer. The conditions in which other two algorithms as sign magnitude and one that use Ones complement fail are following:
  1. They generate ambiguity as there are two numerical 0’s as +0 and -0 represented by these algorithms.
  2. The range of represented no. that produced from these is small.

How:

The algorithm is as follows:-

1. Take  the input binary no.
2. Check  the MSB (most significant bit).
3. If  MSB is 0:
4.   Assign the sign = +ve
5.   Calculate the magnitude by converting n bit no. into decimal.
6. Else:
7.   Assign sign = -ve
8.   Calculate the two’s complement of the binary no.
9.   Calculate the magnitude by converting the two’s complement binary equivalent of the no. to decimal.
10. Print  the magnitude with the sign.
11. END
For example. :
Consider the input : 0000 and 1111
By following the algorithms –
1).
MSB = 0
Sign = +ve
Complement (0000) = 0000
Magnitude = 0
And so on from 1 to 7 are generated from (0001, 0010, 0011, 0100, 0101, 0110, 0111)
2).
MSB = 1
Sign = -ve
Complement (1001) = 0111
Magnitude = 7
And so on till -1 from (1001, 1010, 1011, 1100, 1101, 1110, 1111)

As we can see, there is no ambiguity for 0. Also consider:
Input: 1000
MSB = 1
Sign = -ve
Complement (1000) = 1000
Magnitude = 8
It gives -8, hence increasing the range of possible represented numbers.

Signed magnitude algorithm

:
The MSB is designated for the sign, and magnitude is calculated from n-1 bits.
1. If MSB = 0:
2.   Sign = +ve
3.   Magnitude = decimal ((n-1) bits)
4. Else:
5.   Sign = -ve
6.   Magnitude = decimal ((n-1) bits)
7. Print sign magnitude
8. END
Example input:
0000 , 1000
1).
MSB = 0
Sign = +ve
Magnitude = 0
2).
MSB = 1
Sign = -ve
Magnitude = 0
Ambiguous as here are two 0s, also the range is from +0 to +7 and -0 to -7.

One’s complement Algorithm:

The algorithm is same as two’s complement but we take one’s complement instead of two’s complement of negative signed number.
Example input: 0000, 1111
1).
MSB = 0
Sign = +ve
Magnitude = 0
2).
MSB = 1
Sign = -ve
Magnitude = 0
Again it is also ambiguous and range is also +0 to +7 and -0 to -7.