Source for itoa - T_5B.C [1/1] 
Author Message
 Source for itoa - T_5B.C [1/1]


>Here is a (slightly obfuscated) shorter & faster version...
>void itoa(char *s, int a)
>        int b;

>        for(a<0?b=(*s++='-',-a):a;a;a=a/10) s++;
>        for(*s='\0';b;b=b/10) *--s=b%10+'0';

Your function produced warnings in Borland C, however a slightly
unobfuscated version works fine, except for one number. With -32,768 /
0x8000 as input, your itoa created a garbage string. In all Intel based
PC's the negation (2's complement) of the signed integer 0x8000 is
0x8000. In other words -32,768 remains the same negative number, when
you use the %operator the remainder is a negative number and creates
your string error. The code below fixes this problem by simply changing
int b to an unsigned int b.

void itoa(char *s, int a)
     unsigned int b;                     /* CHANGED FROM: int b */
     if (a < 0) b = -a, *s++ = '-';
     else b = a;
     for(;a;a=a/10) s++;
     for(*s='\0';b;b=b/10) *--s=b%10+'0';
/*                              ^ b is an unsigned int so 0x8000 is */
/* is processed as a unsigned number creating a unsigned remainder  */


In your function, if ( a == 0) you have an empty string, you should add
something like:
if ( a == 0){ strcpy(s,"0");return;}

or since speed is specified:
if ( a == 0){ *s++ ='0';*s='\0';return;}

Calling functions has an overhead in code size and speed, for something
as simple as this you should avoided any function calls inside the

C language negations are proper on 16 bit systems except for this quirk:

If a signed int  b = 0x8000 = -32768
     then b = -b;  leaves the number unchanged.

If a signed char c = 0x80   = -128
     then c = -c;  leaves the number unchanged.

This is a quirk in the system introduced, defined, and documented in the
mnemonic op codes of Intel 16bit CPU's (NEG will set overflow and carry
bits if either of the above situations occur but as a C programmer, you
have no access to the CPU flags). You more or less take cautionary note
of this quirk and program around it.


Yeah...well... this is my token posting. It is a platform specific C
language reply, improper for this group. It would be proper for a new
group such as comp.lang.c.general.

Just to save time, let me reply to any critical response of this
posting: "It ain't perfect, IMHO - perfection is reserved for the truly

Fri, 25 Aug 2000 03:00:00 GMT  
 [ 1 post ] 

 Relevant Pages 

1. Source for itoa

2. Need source for ITOA function

3. Compile CS source code using ICodeCompiler

4. cs source code

5. Newbie: separate big .cs file into small .cs files

6. ITOA without the '\0' terminator

7. Unix version of itoa() ??

8. ansi substitution for itoa?

9. recursive itoa function?

10. itoa function???....

11. itoa question

12. itoa on the mac


Powered by phpBB® Forum Software