integer to string conversion

Chris Torek chris at mimsy.UUCP
Mon Jul 24 15:51:55 AEST 1989


In article <9813 at csli.Stanford.EDU> poser at csli.Stanford.EDU (Bill Poser) writes:
>One way to put an integer into a character string is to use sprintf(3),
>e.g.:	sprintf(string,"%d",foo);
>If you are doing a lot of conversions it may be worthwhile to
>use a special-purpose function.

First, however, make sure that the special-purpose function is both
needed and correct!

[many bits of code deleted below]
>int k;					/* Integer to convert */
>   register int n;
>   int sign;
>   n = k;			/* Copy integer into register */
>   if( (sign = n) < 0) n = -n;	/* Make n positive */

If ints are 16 bits wide and represented in two's complement, the
routine will not produce the right answer for -32768.  If ints are
32 bits wide, the troublesome number will be -2 147 483 648.

>   /* Do conversion */
>   do {
>      q = n / 10;
>      r = (q << 3) + (q << 1);	/* Multiply by 10 (8x + 2x = 10x) */
>      *s++ = n + '0' - r;
>   } while (( n = q) > 0);

If you really need speed, use a binary search to find the range (unless
the range is known to be clustered), then use bits of in-line code to
convert from binary to BCD or equivalent.  Unfortunately, this requires
knowing the range represented by integers.  You will also have to include
a special case for the most negative integer, or use unsigned integers;
on some machines, unsigned comparisons are slower than signed, and on
others the reverse is true.

This sort of thing is generally best left hidden....
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list