home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / LTOA.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  81 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  LTOA.C -- routine and example program to convert a long int to
  5. **  the specified numeric base, from 2 to 36.
  6. **
  7. **  Written by Thad Smith III, Boulder, CO. USA  9/06/91 
  8. **  and contributed to the Public Domain.
  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 (2-36)
  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 "numcnvrt.h"
  21.  
  22. #if defined(__ZTC__) && !defined(__SC__)
  23.  
  24. char *ltoa(
  25.       long val,                                 /* value to be converted */
  26.       char *buf,                                /* output string         */
  27.       int base)                                 /* conversion base       */
  28. {
  29.       ldiv_t r;                                 /* result of val / base  */
  30.  
  31.       if (base > 36 || base < 2)          /* no conversion if wrong base */
  32.       {
  33.             *buf = '\0';
  34.             return buf;
  35.       }
  36.       if (val < 0)
  37.             *buf++ = '-';
  38.       r = ldiv (labs(val), base);
  39.  
  40.       /* output digits of val/base first */
  41.  
  42.       if (r.quot > 0)
  43.             buf = ltoa ( r.quot, buf, base);
  44.  
  45.       /* output last digit */
  46.  
  47.       *buf++ = "0123456789abcdefghijklmnopqrstuvwxyz"[(int)r.rem];
  48.       *buf   = '\0';
  49.       return buf;
  50. }
  51.  
  52. #endif
  53.  
  54. #ifdef TEST
  55.  
  56. #include <stdio.h>
  57.  
  58. main()
  59. {
  60.       char buf[100], line[100], *tail;
  61.       long v;
  62.       int inbase, outbase;
  63.  
  64.       for (;;)
  65.       {
  66.             printf ("inbase, value, outbase (or hit Ctrl-C to exit)? ");
  67.             fgets (line, sizeof line, stdin);
  68.             sscanf (line, " %d%*[, ]%[^, ]%*[, ]%d", &inbase, buf, &outbase);
  69.             if (inbase == 0)
  70.                   break;                        /* exit if first number 0 */
  71.             v = strtol (buf, &tail, inbase);
  72.             printf("%s(%d) = %ld(10)\n", buf, inbase, v);
  73.             ltoa ( v, buf, outbase);
  74.             printf("ltoa(%ld, buf, %d) = %s\n\n", v, outbase, buf);
  75.             printf ("=%ld (10) = %s (%d).\n", v, buf, outbase);
  76.       };
  77.       return 0;
  78. }
  79.  
  80. #endif /* TEST */
  81.