Path: utzoo!attcan!uunet!dino!uxc.cso.uiuc.edu!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: integer to string conversion Keywords: code Message-ID: <18702@mimsy.UUCP> Date: 24 Jul 89 05:51:55 GMT References: <3020@ohstpy.mps.ohio-state.edu> <9813@csli.Stanford.EDU> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 39 In article <9813@csli.Stanford.EDU> poser@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@mimsy.umd.edu Path: uunet!mimsy!chris