home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / programm / 2437 < prev    next >
Encoding:
Text File  |  1992-08-23  |  2.3 KB  |  70 lines

  1. Path: sparky!uunet!seismo!black
  2. From: black@seismo.CSS.GOV (Mike Black)
  3. Newsgroups: comp.programming
  4. Subject: Re: Detecting Integer Overflow/Underflow
  5. Message-ID: <51147@seismo.CSS.GOV>
  6. Date: 23 Aug 92 12:36:17 GMT
  7. References: <1992Aug21.182206.15853@progress.com>
  8. Sender: usenet@seismo.CSS.GOV
  9. Organization: Center for Seismic Studies, Arlington, VA
  10. Lines: 57
  11. Nntp-Posting-Host: beno.css.gov
  12.  
  13. In article <1992Aug21.182206.15853@progress.com> erf@progress.com writes:
  14. >
  15. >Given: Two numbers (integers) of the same bit-width (e.g., they're
  16. >both stored as 16-bit integers), and writing in "C" (with no access to
  17. >the assembly language of the machine; it must be portable!) is it
  18. >possible to write code to detect whether the result of adding,
  19. >substracting or multiplying the two numbers will result in overflow or
  20. >underflow?  The detection can be done either before or after the
  21. >operation.  It should, of course, be as efficient as possible, but any
  22. >solutions are welcome.
  23. >
  24.  
  25. I already mailed a reply to this, but after seeing the postings thought
  26. I should add it here:
  27.  
  28. Since the person wants a solution that is portable, in C, and addresses
  29. addition, subtraction, and multiplication a solution is quite 
  30. straightforward.  USE LONGS!  Simply caste the operands into longs,
  31. perform the math, and check the answer.  If the answer is within 16-bit
  32. limits (signed or unsigned) return the answer else set overflow.
  33.  
  34. #define MAXINT 32767
  35. #define MININT -32768
  36.  
  37. int
  38. add(short num1,short num2,short *sum)
  39. {
  40.     long lnum1,lnum2,lsum;
  41.     lnum1 = num1;
  42.     lnum2 = num2;
  43.     lsum = num1 + num2;
  44.     if (lsum > MAXINT || lsum < MININT) return -1;
  45.     else {
  46.         *sum = lsum;
  47.         return 0;
  48.     }
  49. }
  50.  
  51. main()
  52. {
  53.     int overflow;
  54.     short i,j,sum;
  55.     for(i=1,j=1;;i*=2,j*=2) {
  56.         overflow = add(i,j,&sum);
  57.         printf("%d %d %d\n",overflow,i,j,sum);
  58.         if (overflow) exit(0);
  59.     }
  60. }
  61.  
  62. The same logic works for subtration and multiplication, just change
  63. the operator in the routine.
  64. Mike...
  65. -- 
  66. -------------------------------------------------------------------------------
  67. : usenet: black@beno.CSS.GOV   :  land line: 407-676-2923  : I want a computer:
  68. : real home: Melbourne, FL     :  home line: 407-242-8619  : that does it all!:
  69. -------------------------------------------------------------------------------
  70.