Tuesday, 20 September 2016

Converting from a 2's Compliment Representation to Decimal Representation

If you are into designing arithmetic circuits, or interacting with digital systems, you would have definitely encountered 2's Compliment Scheme for representing the integers in the system. 

Most of the modern day computers; including the most advanced of SoCs in today's existing systems or the one's which will come in future; use predefined macro cells with the logic for doing these operations.

You will not be designing these cells but you'll definitely be using those cells from the standard libraries. The first question that arises here : If these designs already exist and I have to only use them, then why do I care how it is implemented?

Yes, you are right, it doesn't matter how it is implemented but what matters is to understand how the concept works. In other words, one should simply understand how the arithmetic block works or what is the output it should give provided a set of input.

This post is about converting from a 2's compliment representation of binary number to an integer representation. 

The assumption here is that one understands the base system for representing any number.

If we are representing a  number with fixed number of bits in binary representation, then the leftmost bit is treated as the Most Significant Bit (or MSB). In 2's Compliment Notation, this bit decides the sign of the decimal number. The agreement is : If the MSB is 0 then it is a positive integer, else it is a negative number.

Now if the MSB is 0, then it is relatively straightforward to calculate the decimal number as shown in example below (for the sake of explaining we will consider 6 bit binary representation) :

Consider the number 001100, the equivalent decimal number will be equal to 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = 12
We simply multiplied the corresponding bits with the appropriate position in terms of powers of 2 like in the decimal system.

Now let's see how do convert the number when MSB is 1. 
Consider the number 101100, the equivalent decimal number will be equal to (-1)*2^5 + 0*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = -32 + 12 = -20.

The trick here is simple. The position of the MSB remains the same(i.e. the power of 2 associated with the position stays the same. In above example the power of 2 associated with MSB is 5) but we associate a weight of (-1) with the bit.

The trick above is applicable to calculation of positive integers also (Please note that in case of positive integers, the value of MSB is 0 so the contributing factor comes out as (-1)*0*2^(MSB-1) = 0).

Hope that above trick will speed up your calculations while handling 2's compliment representation.

Provide your feedback and responses in comments below !!

Till the next post !!


No comments:

Post a Comment