Question
How do I get the absolute value of a 2s complement negative number so that I can use it as a REAL value?
Answer
a. It is not possible to convert a 2s complement negative number directly to a REAL value.
b. Example 1 below uses V2000 as the 2s complement data source and V3000 as our converted REAL value destination.
i. When a 2s complement value is negative, the most significant bit of the word will be turned on. Therefore, we check to see if V2000 is greater than hex 8000.
ii. If the value in V2000 is less than hex 8000, the value is positive and we can convert using BTOR directly. (Rung 1)
iii. If the value in V2000 is negative, we invert the bit pattern, add 1 to it and store 16 bit result in V3002. We then convert the positive value in V3002 to REAL, multiply it by -1 and store the result in V3000.
Click here for 2s complement ladder Example 1.
c. Example 2 below uses V2000 as the 2s complement data source and V2500 as our converted REAL value destination.
i. When a 2s complement value is negative, the most significant bit of the word will be turned on. In this example we use the actual most significant bit (B2000.15) to determine if value in V2000 is positive or negative.
ii. If the value in V2000 is positive, we convert to REAL using BTOR directly. (Rung 3)
iii. If the value in V2000 is negative, we invert the bit pattern, ANDD the inverted value with KFFFF, add 1 to it, convert the positive value to REAL using BTOR, multiply by -1 and store the result in V2500.
iv. It is important to note that we did not have to store the positive result in an intermediate address in this example. The result of the INV instructions is a 32 bit word stored to the accumulator. Since, we are only dealing with a 16 bit word, we need to mask (get rid of) the most significant 16 bits. To do this we use the ANDD with a value of KFFFF, which turns on only the bottom 16 bits of a 32 bit pattern.
Click here for 2s complement ladder Example 2.
FAQ Subcategory: CPU & Programming
This item was last updated on 2009-03-23
Document ID: 1183
The information provided in the AutomationDirect
knowledge base is provided "as is" without warranty of any
kind. AutomationDirect disclaims all warranties, either
express or implied, including the warranties of
merchantability and fitness for a particular purpose. In no
event shall AutomationDirect or its suppliers be liable
for any damages whatsoever including direct, indirect,
incidental, consequential, loss of business profits or
special damages, even if AutomationDirect or its
suppliers have been advised of the possibility of such
damages. Some states do not allow the exclusion of
limitation of liability for consequential or incidental
damages so the foregoing limitation may not apply.