Skip to Content.
Sympa Menu

freetds - tds_atoi and numeric format

freetds AT lists.ibiblio.org

Subject: FreeTDS Development Group

List archive

Chronological Thread  
  • From: ZIGLIO Frediano <Frediano.Ziglio AT vodafoneomnitel.it>
  • To: "Freetds (E-mail)" <freetds AT franklin.metalab.unc.edu>
  • Subject: tds_atoi and numeric format
  • Date: Tue, 6 Aug 2002 14:14:23 +0200


Current cvs tds_atoi have some problem.
Converting "-pippo" just return 0.
atoi return 0 on error (some implementation even on overflow, other return
strange number) so unrecognid string return 0 (there is no way to understand
reason for 0).

I rewritten an implementation who care this problem (first idea was using
strtol but check overflow with errno can give threadsafe problem on some
platform).

TDS_INT
tds_atoi(const char *buf,TDS_INT* res)
{
enum { blank = ' ' };
const char *p;
int sign;
unsigned int num,n; /* we use unsigned here for best overflow check */

p = buf;

/* ignore leading spaces */
while( *p == blank )
++p;

/* check for sign */
sign = 0;
switch ( *p ) {
case '-':
sign = 1;
/* fall thru */
case '+':
/* skip spaces between sign and number */
while( *++p == blank );
break;
}

/* a digit must be present */
if (!*p)
return TDS_FAIL;

num = 0;
for(;*p;++p) {
/* check for trailing spaces */
if (*p == blank) {
while( *++p == blank);
if (*p) return TDS_FAIL;
break;
}

/* must be a digit */
if (!isdigit(*p))
return TDS_FAIL;

/* add a digit to number and check for overflow */
n = num * 10 + (*p-'0');
if (n < num)
return TDS_FAIL;
num = n;
}

/* check for overflow and convert unsigned to signed */
if (sign) {
if (num > 2147483648u)
return TDS_FAIL;
num = -num;
} else {
if (num >= 2147483648u)
return TDS_FAIL;
}

*res = num;
return TDS_SUCCEED;
}

Some question. Are you sure that library ignore blanks between sign and
digits (select convert(int, ' - 13 ') is not a good test, this is the
behaviour of sql server, not libraries)?
What about conversion to TDS_INT8? Perhaps this function should be changed
to return a TDS_INT8 instead a TDS_INT?

freddy77

=================================
"STRICTLY PERSONAL AND CONFIDENTIAL

This message may contain confidential and proprietary material for the sole
use of the intended recipient. Any review or distribution by others is
strictly prohibited. If you are not the intended recipient please contact
the sender and delete all copies.
The contents of this message that do not relate to the official business of
our company shall be understood as neither given nor endorsed by it."

=================================




Archive powered by MHonArc 2.6.24.

Top of Page