FX Series Programmable Controllers | Devices in Detail 4 |
4.14.4Two’s Compliment
Programmable controllers, computers etc, use a format called 2’s compliment. This is a mathematical procedure which is more suited to the micro processors operational hardware requirements. It is used to represent negative numbers and to perform subtraction operations. The procedure is very simple, in the following example “15 - 7” is going to be solved:
Step1: Find the binary values (this example uses 8 bits)
15 | = | 00001111 |
7 | = | 00000111 |
Step2: Find the inversion of the value to be subtracted.
Procedure: invert all 1ís to 0ís and all 0ís to 1’s.
7 | = | 00000111 |
Inverted 7 | = | 11111000 |
Step3: Add 1 to the inverted number.
Procedure: add 1 to the right hand most bit. Remember this is binary addition hence, when a value of 2 is obtained 1 is moved in to the next left hand position and the remainder is set to 0 (zero);
Inverted7 11111000
Additional1 00000001
Answer 11111001
This result is actually the same as the negative value for 7 i.e.
Step4: Add the answer to the number the subtraction is being made from (i.e. 15).
Procedure: Remember 1+1 = 0 carry 1 in base 2 (binary).
Original value15 | 00001111 |
Answer found in step3 | 11111001 |
Solution | (1)00001000 |
The “(1)” is a carried “1” and is ignored as this example is only dealing with 8 bits.
Step 5: Convert the answer back. 00001000 = 8
The answer is positive because the MSB (the most left hand bit) is a 0 (zero). If a quick mental check is made of the problem it is indeed found that
In fact no subtraction has taken place. Each of the steps has either converted some data or performed an addition. Yet the answer is correct 15 - 7 is 8. This example calculation was based on 8 bit numbers but it will work equally well on any other quantity of bits.