We are a well-established online store offering customized goods and merchandise for passionate people.
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:
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.
We wish to write out 28 in Two’s complement. Firstly we will write down 28 in binary form.
Then we invert the digits. 0 becomes 1, 1 becomes 0.
Then we add 1 to the least significant bit i.e the rightmost bit.
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:
Invert the digits.
And add one.
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.
Overflow mostly occurs when adding two binary numbers together. An
overflow occurs if the two numbers being added have the same sign bit
and the result has the opposite sign bit. For instance, 2 positive
numbers when added together yield a negative answer.
Another instance can be when the final output exceeds the range (?8 ? x ? +7).
No overflow occurs when a positive number is added to a negative number.
(-13) 1 0011 = 3
In this example, the leftmost 1 is an overflow bit.
We also know an overflow has occurred here because the lowest possible number for a 4-bit binary string is -8. -13 obviously exceed the range.
This is all there is to Two’s complement and you can now start solving your sums.
Create your free account to unlock your custom reading experience.