"M. Edward Wilborne III" <[EMAIL PROTECTED]> writes:

> The real question, is, IMHO, "Is there an overflow carry when A+B get
> added?"
> 
> So, if you right shift by 1 bit a and b, (i.e. divide each by 2) and then
> add those divided numbers together, then the resulting answer will have the
> high order bit set if the numbers when added (unshifted) would have caused
> and "overflow".
> 
> There's probably an easy way to test this using subtraction...

Simple algebra.

To avoid overflow, the following equation must hold:

  a + b <= maxint

Rearranging terms:

  a <= maxint - b

Therefore, 

  if (a <= maxint - b) {
    // no overflow, safe to add
  }

It gets a little more complicated if you're using signed ints.

-- 
Dave Carrigan ([EMAIL PROTECTED])            | Yow! Can you MAIL a BEAN CAKE?
UNIX-Apache-Perl-Linux-Firewalls-LDAP-C-DNS | 
Seattle, WA, USA                            | 
http://www.rudedog.org/                     | 

-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/tech/support/forums/

Reply via email to