Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 8a5a16fa99888cb1f818a8ae5e09c7367c833622
Ticket: 452032ffffffffffffffffffffffffffffffffff
Some Strings Incorrectly Convrtd To Ints
User & Date: dtashley on 2001-08-18 01:44:43
Changes

  1. icomment:
    Logged In: YES 
    user_id=234929
    
    Dear Mr. Sofer,
    
    The text below is from a newsgroup post.
    
    Please let me know if you want me to make the change.  In 
    other words, I can examine the CVS archives, read-only, 
    work out the details and ... blah.  Does the information 
    below give you enough of a blueprint for STRING->INT 
    conversion, should I go further, how can I assist, etc.?
    
    Thanks, Dave.
    
    OK, included in this post is a replacement for the 
    SetIntFromAny() function.
    Of course, one might want to modify it a little bit so that 
    it parses longs
    and ints at the same time, but the fundamental results are 
    sound.  I'll
    discuss it in detail.  I'll also post it along with my 
    original bug report
    in case it is helpful.
    
    Here are all the points to make.
    
    Second, the reason I don't like the Tcl code to do with 
    parsing integers is
    that in any software that deals with strings, somewhere you 
    have to have an
    unequivocal "language membership arbiter".  In other words, 
    you have to have
    a clear idea of what strings can represent an integer and 
    what cannot, and
    that should be concentrated in one place in the software.  
    You need a clear
    membership function, which should be one and only one place 
    in the software.
    The Tcl function calls a library function, and I don't like 
    that because
    those library functions are notoriously sloppy and don't 
    make good
    membership functions.  It is better not to use such library 
    functions.
    
    Third, the notion of what is a valid string representation 
    of an integer and
    what is not is very intimately related to the activity of 
    converting the
    string to an integer.  It is easiest to combine the two 
    functionalities.
    For example, in the function I'm providing below, it would 
    also be a
    "membership arbiter".  If some client wanted to know if a 
    string was a valid
    integer (but not necessarily to convert it), it would still 
    use the function
    below, but just would not use the integer result.  It is 
    easiest to combine
    the notion of MEMBERSHIP TESTING and of CONVERSION into the 
    same
    function--the activities are related.
    
    Fourth, some people will look at the code below and wonder 
    about the
    efficiency.  It is very efficient.  There really is not a 
    more efficient
    algorithm for parsing an integer than the classic add and 
    multiply.  There
    could be some economies made, such as assigning *s to a 
    char variable so the
    pointer is not repeatedly dereferenced, etc.  But, at the 
    core, this is the
    most efficient algorithm.  Note that the steps going in 
    (such as determining
    the largest integer that you can multiply by 10 without an 
    overflow) are
    very efficient, and require an IDIV or similar.  Also, the 
    tests while
    looping are generally single machine instructions.
    
    Fifth, if the function below is to be combined with long 
    integer parsing,
    the recommended approach would be to ALWAYS parse long 
    integers, then test
    at the end if it will fit into an integer.  There are size-
    independent ways
    to obtain the smallest and largest integers to compare 
    against.
    
    Sixth, as far as size-independence, the function below is 
    fully portable.
    There are just a few tricks necessary to work with integers 
    where you don't
    know the size in advance.  To get the largest positive 
    integer, the general
    procedure is:
    
    (int)((unsigned)(-1) >> 1)
    
    and this is below.
    
    To get the most negative integer, the result above is 
    normally complemented,
    i.e.
    
    (int)(~((unsigned)(-1) >> 1))
    
    These represent bit patterns of 01111...1111 and 
    1000...0000, respectively.
    
    I welcome any dissent about the function below.
    
    I do not like the Tcl code because it is .... .... 
    unreliable.
    
    Best regards, Dave.
    
    //s--string in.
    //*result -- integer out.
    //*failure -- if TRUE, the the conversion failed and it is 
    not an integer.
    void string_to_arbitrary_int(const char *s, int *result, 
    int *failure)
       {
       int neg;
          //TRUE if '-' sign encountered.
       int rv;
          //Value that will be returned.
       int pos_mul_ten_threshold;
          //A number this large is the largest number that we 
    can
          //multiply by 10 and still have a valid positive 
    result.
          //We also know that this, negated, is the negative 
    threshold.
          //
          //The reason we know this is as follows.  First, no 
    power of
          //two can also be a multiple of ten, due to the 
    fundamental theorem
          //of arithmetic and the absence of 5 as a prime 
    factor.  Second,
          //no power of two plus one or minus one can be a 
    multiple of ten,
          //because such a number would be odd.  Therefore, the 
    following
          //is true:
          //
          //   a)The maximum positive value of a signed integer 
    is not
          //     a multiple of 10.
          //   b)The maximum negative value of a signed integer 
    is not
          //     a multiple of 10.
          //
          //Assume we compute a postive threshold.  Then we 
    know the
          //following:
          //   threshold < MAXPOSINT < 10 * threshold
          //
          //We also then know that:
          //   -threshold > MAXNEGINT > 10 * -threshold
          //
          //We can deduce this because (10 * threshold) is a 
    multiple of
          //10, but neither MAXPOSINT nor MAXNEGINT can be.
       int neg_mul_ten_threshold;
          //Negative of above, calculated once to save time.  
    As mentioned
          //above, don't need to calc this separately.
    
       int temp;
          //General temporary int.
    
       //As the first order of business, be sure that the 
    caller isn't
       //being stupid.
       //assert(s       != NULL);
       //assert(result  != NULL);
       //assert(failure != NULL);
    
       //Compute the maximum positive number that we can 
    multiply by
       //10 and still get a positive result without overflow.  
    This
       //should be one integer div instruction.  The following 
    should
       //be integer size independent.  The cast is necessary to 
    guarantee a
       //zero in the MSB position.
       pos_mul_ten_threshold = ((int)((unsigned)-1 >> 1)) / 10;
       neg_mul_ten_threshold = - pos_mul_ten_threshold;
    
       //If first char is a minus sign, note it and advance 
    past it.
       neg = 0;
       if (*s == '-')
          {
          neg = 1;
          s++;
    
          //You cannot negate zero.
          if (*s == '0')
             goto failure_return;
          }
    
       //An empty string is not an integer!
       if (!*s)
          goto failure_return;
    
       //If zero appears, it cannot be leading--this is not a 
    well-formed
       //integer.  Non-zero integers don't begin with zero, and 
    the
       //only valid representation of zero is the single digit 
    zero.
       if (*s == '0')
          {
          if (!s[1])
             {
             //We have a zero with nothing else.  Fine.
             rv = 0;
             goto success_return;
             }
          else
             {
             //We have a zero with trash after it.  This is 
    illegal.
             goto failure_return;
             }
          }
    
       //Gotta handle the first digit as a special case, 
    otherwise
       //complexity later.
       if (*s < '0' || *s > '9')  //Gotta be a digit.
          goto failure_return;
    
       rv = *s - '0';
       s++;
    
       //Negate and get going negative if had a minus sign.
       if (neg)
          {
          rv = -rv;
          }
    
       while (*s)
          {
          //Gotta be a digit.
          if (*s < '0' || *s > '9')
             goto failure_return;
    
          //The multiplication before we add can't overflow 
    us.  We
          //calculated the threshold in a machine-independent 
    way earlier.
          if (rv < neg_mul_ten_threshold || rv > 
    pos_mul_ten_threshold)
             goto failure_return;
    
          //We are guaranteed clear for the multiplication.
          rv *= 10;
    
          //Now need to add (or subtract) the digit.
          //We will always add (or subtract) a value
          //in the range of 0..10.  How do we detect overflow?
          //If we have a positive integer, an overflow sets the
          //sign bit, so we can detect it that way.  If we have
          //a negative integer, in order to overflow, we need
          //to be within 10 counts of the negative maximum.  It 
    is
          //easy to show that such a number will lose its sign 
    bit
          //when overflowed.
          temp = *s - '0';
          if (neg)
             {
             //Negative case.
             rv -= temp;
             if (rv >= 0)
                {
                //Ouch, overflow.
                goto failure_return;
                }
             }
          else
             {
             rv += temp;
             if (rv < 0)
                {
                //Ouch, overflow.
                goto failure_return;
                }
             }
    
          //Advance to next character.
          s++;
          }
    
       success_return:
          *failure = 0;
          *result = rv;
          return;
       failure_return:
          *failure = 1;
          return;
       }
    
    
    
  2. login: "dtashley"
  3. mimetype: "text/plain"
  4. username: "dtashley"