home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!seismo!black
- From: black@seismo.CSS.GOV (Mike Black)
- Newsgroups: comp.programming
- Subject: Re: Detecting Integer Overflow/Underflow
- Message-ID: <51147@seismo.CSS.GOV>
- Date: 23 Aug 92 12:36:17 GMT
- References: <1992Aug21.182206.15853@progress.com>
- Sender: usenet@seismo.CSS.GOV
- Organization: Center for Seismic Studies, Arlington, VA
- Lines: 57
- Nntp-Posting-Host: beno.css.gov
-
- In article <1992Aug21.182206.15853@progress.com> erf@progress.com writes:
- >
- >Given: Two numbers (integers) of the same bit-width (e.g., they're
- >both stored as 16-bit integers), and writing in "C" (with no access to
- >the assembly language of the machine; it must be portable!) is it
- >possible to write code to detect whether the result of adding,
- >substracting or multiplying the two numbers will result in overflow or
- >underflow? The detection can be done either before or after the
- >operation. It should, of course, be as efficient as possible, but any
- >solutions are welcome.
- >
-
- I already mailed a reply to this, but after seeing the postings thought
- I should add it here:
-
- Since the person wants a solution that is portable, in C, and addresses
- addition, subtraction, and multiplication a solution is quite
- straightforward. USE LONGS! Simply caste the operands into longs,
- perform the math, and check the answer. If the answer is within 16-bit
- limits (signed or unsigned) return the answer else set overflow.
-
- #define MAXINT 32767
- #define MININT -32768
-
- int
- add(short num1,short num2,short *sum)
- {
- long lnum1,lnum2,lsum;
- lnum1 = num1;
- lnum2 = num2;
- lsum = num1 + num2;
- if (lsum > MAXINT || lsum < MININT) return -1;
- else {
- *sum = lsum;
- return 0;
- }
- }
-
- main()
- {
- int overflow;
- short i,j,sum;
- for(i=1,j=1;;i*=2,j*=2) {
- overflow = add(i,j,&sum);
- printf("%d %d %d\n",overflow,i,j,sum);
- if (overflow) exit(0);
- }
- }
-
- The same logic works for subtration and multiplication, just change
- the operator in the routine.
- Mike...
- --
- -------------------------------------------------------------------------------
- : usenet: black@beno.CSS.GOV : land line: 407-676-2923 : I want a computer:
- : real home: Melbourne, FL : home line: 407-242-8619 : that does it all!:
- -------------------------------------------------------------------------------
-