Author Topic: Detecting Multiplication Overflow  (Read 11753 times)

eagroup

  • Newbie
  • *
  • Posts: 4
  • I'm a llama!
    • View Profile
Detecting Multiplication Overflow
« on: November 26, 2014, 12:02:56 PM »
I am multiplying four 32-bit values in variables G, I, J and K and putting the result in L (in a single TBasic statement).  Is there a way to detect if the result has overflowed L?  I've only found references in the documentation to avoid overflowing, but nothing on how the program can detect it when it happens.

support

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 3174
    • View Profile
    • Internet Programmable PLCs
Re:Detecting Multiplication Overflow
« Reply #1 on: November 26, 2014, 01:45:36 PM »
There is no built-in mechanism for detecting 32-bit overflow. If all the numbers you are dealing with are positive then sudden change of sign should be an indication that the multiplication has overflowed.

If you frequently deal with very large number a simpler solution may be to upgrade to the Fx class PLC which handles floating point math - much bigger room before overflow occurs.

Another way I can think of is to call a function to compute the order of magnitude (in terms of the power of 10) of each of the numbers to be involved in a multiplication. You can accomplish this by using a while loop to divide the number by 10 until you get a zero and you will then know the order of magnitude. Since the maximum number the 32-bit integer can handle is approx 2 x 10^9 you can add up their respective order of magnitudes to see if they exceed 9 and you then would know if the multiplication will overflow.
Email: support@triplc.com
Tel: 1-877-TRI-PLCS