home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!idacrd!desj@ccr-p.ida.org
- From: desj@ccr-p.ida.org (David desJardins)
- Newsgroups: comp.programming
- Subject: Re: Detecting Integer Overflow/Underflow
- Message-ID: <1572@idacrd.UUCP>
- Date: 22 Aug 92 20:44:12 GMT
- References: <1992Aug21.182206.15853@progress.com> <HUDGENS.92Aug22113851@sun13.SCRI.FSU.EDU>
- Sender: desj@idacrd.UUCP
- Organization: IDA Center for Communications Research, Princeton
- Lines: 59
-
- Jim Hudgens <hudgens@SCRI.FSU.EDU> writes:
- >Sample code for adding two 16 bit integers and setting the overflow
- >flag based on the result (it's part of an 8086 emulator) follows.
-
- >But there has *got* to be a better (i.e. faster) way. This is one
- >of the major reasons I can't get >PC/XT speeds running on a Sun SS1.
-
- Your code seems much too complicated to understand! The following is
- much easier. It just relies on the fact that overflow occurs iff a and
- b have the same sign, and a+b has the opposite sign.
-
- I've also included code for unsigned overflow. (It wasn't specified in
- the original posting which was required.) This computes the same
- quantity that Jim called cc, but with four operations instead of five.
-
- By the way, I think it is a shame that most computer scientists are
- taught that a good way to synthesize boolean functions is with a
- Karnaugh map. This is somewhat reasonable for a hardware engineer using
- only NAND gates, but for a more general computational model, it's rarely
- a good idea. I remember vividly scoring 110 out of 100 on a test at MIT
- on which one of the questions was, "Synthesize this function with the
- minimum number of gates," and I did better than the "correct" solution
- which used a Karnaugh map.)
-
- I suspect the general problem is NP-hard, which is probably why they
- don't teach an optimal algorithm :-).
-
- David desJardins
-
-
- #define WORDSIZE 16
-
- int addint (int a, int b, int &overflow) {
- /* a and b are signed integers, WORDSIZE is the length of each. The
- return value is the sum of a and b, and the value of overflow is 1
- if overflow occurred, or zero otherwise. */
-
- int sum;
- unsigned int temp;
-
- sum = a + b;
- temp = (a ^ sum) & (b ^ sum);
- *overflow = temp >> (WORDSIZE - 1);
- return sum;
- }
-
- unsigned int adduint (unsigned int a, unsigned int b, int &overflow) {
- /* a and b are unsigned integers, WORDSIZE is the length of each. The
- return value is the sum of a and b, and the value of overflow is 1
- if overflow occurred, or zero otherwise. */
-
- unsigned int sum;
- unsigned int temp;
-
- sum = a + b;
- temp = ((a ^ sum) & (a ^ b)) ^ b;
- *overflow = temp >> (WORDSIZE - 1);
- return sum;
- }
-