Menu

Long variable overflow

Help
MBB
2021-03-10
2021-06-02
  • MBB

    MBB - 2021-03-10

    Is there a way to indicate when a multiplication of 2 variables causes a long variable to overflow?

    For example:

    Dim xx, yy, zz as long

    xx = 70000
    yy = 75000

    zz = xx * yy ;should = 5,250,000,000 which is greater than 2^32.

    How would I know zz overflowed?

     
  • Chris Roper

    Chris Roper - 2021-03-10

    To the best of my knowledge GCBASIC, nor any other BASIC Dialect, has no overflow indication.
    In GCBASIC, Long is normally used as a counter or as the product of two Word's.
    If the arguments need to be Long as well then, as GCBASIC has no 64Bit (or Long Long) variable, it is up to the programmer to ensure that the range of values used will not cause an overflow.

     
  • MBB

    MBB - 2021-03-11

    Thanks chris!

     
    • Anobium

      Anobium - 2021-03-11

      There may be a way, but, I had to write and test code to figure out what worked and what did not work.

      I found that C, carry flag, did not represent an overflow.

      Then, I wrote this... seems to work.

      Dim xx, yy, zz as long
      
      xx = 70000
      yy = 61357
      
      wait 1 s
      
      zz = xx * yy
      
      'Re-assemble calc and test result.  
      if (zz/yy)<>xx then
        HSerPrint "Overflow"
      else
        HSerPrint "No Overflow"
      end if
      
      HSerPrint " :"
      HSerPrint zz
      

      Please test.

       
      • Chris Roper

        Chris Roper - 2021-03-11

        Clever, it could be a bit memory intensive as it will need a minimum of 32 bytes plus working space but it should be fine for larger PIC's .

         
        • Anobium

          Anobium - 2021-03-11

          I thought the same... but, could be worth the clock cycles.... :-)

           
  • MBB

    MBB - 2021-03-12

    Wow! So simple and yet so clever. Thanks!

     
    • Anobium

      Anobium - 2021-03-12

      Let us all know if it works!!!

       
  • SPostma

    SPostma - 2021-06-02

    another way might be to take the high bytes of the input values, increment them if the low byte is <> 0, and then multiply those bytes. If the result is < 65536 then no overflow will occur in the full 16 x 16 bit multiplication. This will be faster than doing a 32 bit division.

     

Log in to post a comment.