Two's Complement - How To Calculate And Convert For Binary Numbers
Modern computers today use a binary number representation system called 'Two's complement'. It is a fixed number of binary digits used in computer calculations. Basic math operations such as addition and subtraction can be performed using the binary rules of addition and subtraction. Two's complement is not a complex scheme and is rather very simple to work with. This system also helps overcome the shortcomings of having to deal with magnitudes. Two's complement can be characterized as:
• A fixed number of bits are used to represent numbers i.e 4 bits
• The most significant bit is called the sign bit (the leftmost bit)
• This notation can represent both negative and positive integers.
• The highest positive number that can be represented is 7; the lowest possible number that can be represented is -8 using a 4 bit string.
Positive numbers have a 0 in the most significant (leftmost) position and negative numbers have a 1 in this position. This is why the most significant bit is also called the sign bit.
1101 = -3
0011 = 3
How to convert to Two’s complement?
The process of converting a binary string to a Two’s complement consists of inverting all of the bits in the number, then adding 1 to the least significant bit (rightmost) position.
For example:
We wish to write out 28 in Two’s complement. Firstly we will write down 28 in binary form.
0001 1100
Then we invert the digits. 0 becomes 1, 1 becomes 0.
1110 0011
Then we add 1 to the least significant bit i.e the rightmost bit.
1110 0100
This is the way that one would write -28 in 8-bit binary.
Note the leftmost bit is a 1 which means 28 is a negative integer in this example.
This works both ways as well. You can start with a negative integer but to make our calculations easier we avoid the negative notation initially and then in our final answer adjust the bits to get the desired result.
Take for example -30. We want to represent it in 2's complement, you take the binary representation of +30:
0001 1110
Invert the digits.
1110 0001
And add one.
1110 0010
The final output is the Two’s complement for -30.
Inverting and adding one might sound like a very strange thing to do, but it is actually just a mathematical shortcut and a rather straightforward computation.
Detecting an Overflow
When we are dealing with binary digits, we are often limited in the number of bits we can use. There is usually a fixed number of bits allowed by the system. Therefore we need to stay vigilant in case an overflow occurs.
Know more about two's complement
Comments
Post a Comment