home *** CD-ROM | disk | FTP | other *** search
/ Power Programming / powerprogramming1994.iso / progtool / c / string.arc / STR2INT.C < prev    next >
Text File  |  1984-12-31  |  6KB  |  180 lines

  1. /*  File   : str2int.c
  2.     Author : Richard A. O'Keefe
  3.     Updated: 27 April 1984
  4.     Defines: str2int(), atoi(), atol()
  5.  
  6.     str2int(src, radix, lower, upper, &val)
  7.     converts the string pointed to by src to an integer and stores it in
  8.     val.  It skips leading spaces and tabs (but not newlines, formfeeds,
  9.     backspaces), then it accepts an optional sign and a sequence of digits
  10.     in the specified radix.  The result should satisfy lower <= *val <= upper.
  11.     The result is a pointer to the first character after the number;
  12.     trailing spaces will NOT be skipped.
  13.  
  14.     If an error is detected, the result will be NullS, the value put
  15.     in val will be 0, and errno will be set to
  16.     EDOM    if there are no digits
  17.     ERANGE    if the result would overflow or otherwise fail to lie
  18.         within the specified bounds.
  19.     Check that the bounds are right for your machine.
  20.     This looks amazingly complicated for what you probably thought was an
  21.     easy task.  Coping with integer overflow and the asymmetric range of
  22.     twos complement machines is anything but easy.
  23.  
  24.     So that users of atoi and atol can check whether an error occured,
  25.     I have taken a wholly unprecedented step: errno is CLEARED if this
  26.     call has no problems.
  27. */
  28.  
  29. #include "strings.h"
  30. #include "ctypes.h"
  31. #include <errno.h>
  32. extern int errno;
  33.  
  34. /*    CHECK THESE CONSTANTS FOR YOUR MACHINE!!!    */
  35.  
  36. #if    pdp11
  37. #   define    MaxInt      0x7fffL    /* int  = 16 bits */
  38. #   define    MinInt      0x8000L
  39. #   define    MaxLong 0x7fffffffL    /* long = 32 bits */
  40. #   define    MinLong 0x80000000L
  41. #else  !pdp11
  42. #   define    MaxInt  0x7fffffffL    /* int  = 32 bits */
  43. #   define    MinInt  0x80000000L
  44. #   define    MaxLong 0x7fffffffL    /* long = 32 bits */
  45. #   define    MinLong 0x80000000L
  46. #endif    pdp11
  47.  
  48.  
  49. char *str2int(src, radix, lower, upper, val)
  50.     register char *src;
  51.     register int radix;
  52.     long lower, upper, *val;
  53.     {
  54.     int sign;        /* is number negative (+1) or positive (-1) */
  55.     int n;            /* number of digits yet to be converted */
  56.     long limit;        /* "largest" possible valid input */
  57.     long scale;        /* the amount to multiply next digit by */
  58.     long sofar;        /* the running value */
  59.     register int d;        /* (negative of) next digit */
  60.     char *answer;        
  61.  
  62.     /*  Make sure *val is sensible in case of error  */
  63.  
  64.     *val = 0;
  65.  
  66.     /*  Check that the radix is in the range 2..36  */
  67.  
  68.     if (radix < 2 || radix > 36) {
  69.         errno = EDOM;
  70.         return NullS;
  71.     }
  72.  
  73.     /*  The basic problem is: how do we handle the conversion of
  74.         a number without resorting to machine-specific code to
  75.         check for overflow?  Obviously, we have to ensure that
  76.         no calculation can overflow.  We are guaranteed that the
  77.         "lower" and "upper" arguments are valid machine integers.
  78.         On sign-and-magnitude, twos-complement, and ones-complement
  79.         machines all, if +|n| is representable, so is -|n|, but on
  80.         twos complement machines the converse is not true.  So the
  81.         "maximum" representable number has a negative representative.
  82.         Limit is set to min(-|lower|,-|upper|); this is the "largest"
  83.         number we are concerned with.    */
  84.  
  85.     /*  Calculate Limit using Scale as a scratch variable  */
  86.  
  87.     if ((limit = lower) > 0) limit = -limit;
  88.     if ((scale = upper) > 0) scale = -scale;
  89.     if (scale < limit) limit = scale;
  90.  
  91.     /*  Skip leading spaces and check for a sign.
  92.         Note: because on a 2s complement machine MinLong is a valid
  93.         integer but |MinLong| is not, we have to keep the current
  94.         converted value (and the scale!) as *negative* numbers,
  95.         so the sign is the opposite of what you might expect.
  96.         Should the test in the loop be isspace(*src)?
  97.     */
  98.     while (*src == ' ' || *src == '\t') src++;
  99.     sign = -1;
  100.     if (*src == '+') src++; else
  101.     if (*src == '-') src++, sign = 1;
  102.  
  103.     /*  Check that there is at least one digit  */
  104.  
  105.     if (_c2type[1+ *src] >= radix) {
  106.         errno = EDOM;
  107.         return NullS;
  108.     }
  109.  
  110.     /*  Skip leading zeros so that we never compute a power of radix
  111.         in scale that we won't have a need for.  Otherwise sticking
  112.         enough 0s in front of a number could cause the multiplication
  113.         to overflow when it neededn't.
  114.     */
  115.     while (*src == '0') src++;
  116.  
  117.     /*  Move over the remaining digits.  We have to convert from left
  118.         to left in order to avoid overflow.  Answer is after last digit.
  119.     */
  120.     for (n = 0; _c2type[1+ *src++] < radix; n++) ;
  121.     answer = --src;
  122.  
  123.     /*  The invariant we want to maintain is that src is just
  124.         to the right of n digits, we've converted k digits to
  125.         sofar, scale = -radix**k, and scale < sofar < 0.  Now
  126.         if the final number is to be within the original
  127.         Limit, we must have (to the left)*scale+sofar >= Limit,
  128.         or (to the left)*scale >= Limit-sofar, i.e. the digits
  129.         to the left of src must form an integer <= (Limit-sofar)/(scale).
  130.         In particular, this is true of the next digit.  In our
  131.         incremental calculation of Limit,
  132.  
  133.         IT IS VITAL that (-|N|)/(-|D|) = |N|/|D|
  134.     */
  135.     
  136.     for (sofar = 0, scale = -1; --n >= 0; ) {
  137.         d = _c2type[1+ *--src];
  138.         if (-d < limit) {
  139.         errno = ERANGE;
  140.         return NullS;
  141.         }
  142.         limit = (limit+d)/radix, sofar += d*scale;
  143.         if (n != 0) scale *= radix;    /* watch out for overflow!!! */
  144.     }    
  145.     /*  Now it might still happen that sofar = -32768 or its equivalent,
  146.         so we can't just multiply by the sign and check that the result
  147.         is in the range lower..upper.  All of this caution is a right
  148.         pain in the neck.  If only there were a standard routine which
  149.         says generate thus and such a signal on integer overflow...
  150.         But not enough machines can do it *SIGH*.
  151.     */
  152.     if (sign < 0 && sofar < -MaxLong /* twos-complement problem */
  153.     ||  (sofar*=sign) < lower || sofar > upper) {
  154.         errno = ERANGE;
  155.         return NullS;
  156.     }
  157.     *val = sofar;
  158.     errno = 0;        /* indicate that all went well */
  159.     return answer;
  160.     }
  161.  
  162.  
  163. int atoi(src)
  164.     char *src;
  165.     {
  166.     long val;
  167.     str2int(src, 10, MinInt, MaxInt, &val);
  168.     return (int)val;
  169.     }
  170.  
  171.  
  172. long atol(src)
  173.     char *src;
  174.     {
  175.     long val;
  176.     str2int(src, 10, MinLong, MaxLong, &val);
  177.     return val;
  178.     }
  179.