home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / snip1292.zip / LTOA.C < prev    next >
C/C++ Source or Header  |  1991-09-09  |  2KB  |  59 lines

  1. /*
  2. **  LTOA.C
  3. **
  4. **  Converts a long integer to a string.
  5. **
  6. **  Copyright 1988-90 by Robert B. Stout dba MicroFirm
  7. **
  8. **  Released to public domain, 1991
  9. **
  10. **  Parameters: 1 - number to be converted
  11. **              2 - buffer in which to build the converted string
  12. **              3 - number base to use for conversion
  13. **
  14. **  Returns:  A character pointer to the converted string if
  15. **            successful, a NULL pointer if the number base specified
  16. **            is out of range.
  17. */
  18.  
  19. #include <stdlib.h>
  20. #include <string.h>
  21.  
  22. #define BUFSIZE (sizeof(long) * 8 + 1)
  23.  
  24. char *ltoa(long N, char *str, int base)
  25. {
  26.       register int i = 2;
  27.       long uarg;
  28.       char *tail, *head = str, buf[BUFSIZE];
  29.  
  30.       if (36 < base || 2 > base)
  31.             base = 10;                    /* can only use 0-9, A-Z        */
  32.       tail = &buf[BUFSIZE - 1];           /* last character position      */
  33.       *tail-- = '\0';
  34.  
  35.       if (10 == base && N < 0L)
  36.       {
  37.             *head++ = '-';
  38.             uarg    = -N;
  39.       }
  40.       else  uarg = N;
  41.  
  42.       if (uarg)
  43.       {
  44.             for (i = 1; uarg; ++i)
  45.             {
  46.                   register ldiv_t r;
  47.  
  48.                   r       = ldiv(uarg, base);
  49.                   *tail-- = (char)(r.rem + ((9L < r.rem) ?
  50.                                   ('A' - 10L) : '0'));
  51.                   uarg    = r.quot;
  52.             }
  53.       }
  54.       else  *tail-- = '0';
  55.  
  56.       memcpy(head, ++tail, i);
  57.       return str;
  58. }
  59.