home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 3 / 3571 / atov.c next >
C/C++ Source or Header  |  1991-07-02  |  2KB  |  76 lines

  1. /* +-------------------------------------------------------------------+ */
  2. /* | Copyright 1988,1991, David Koblas.                                | */
  3. /* |   Permission to use, copy, modify, and distribute this software   | */
  4. /* |   and its documentation for any purpose and without fee is hereby | */
  5. /* |   granted, provided that the above copyright notice appear in all | */
  6. /* |   copies and that both that copyright notice and this permission  | */
  7. /* |   notice appear in supporting documentation.  This software is    | */
  8. /* |   provided "as is" without express or implied warranty.           | */
  9. /* +-------------------------------------------------------------------+ */
  10.  
  11. #include    <ctype.h>
  12.  
  13. #ifdef TEST
  14. main(argc,argv)
  15. int    argc;
  16. char    **argv;
  17. {
  18.     int    i;
  19.     for (i=1;i<argc;i++)
  20.         printf("%10s  == %d\n",argv[i],atov(argv[i],0));
  21. }
  22. #endif
  23.  
  24. atov(str,type)
  25. char    *str;
  26. int    type;
  27. {
  28.     int        sign = 1;
  29.     int        i;
  30.     char        c;
  31.     int        val=0,n;
  32.  
  33.     i=0;
  34.     while ((str[i]==' ') || (str[i]=='\t')) i++;
  35.     if (str[i]=='-')  {
  36.         sign = -1;
  37.         i++;
  38.     } else if (str[i]=='+') {
  39.         sign = 1;
  40.         i++;
  41.     }
  42.     if (type==0)  {
  43.         if (str[i]=='0') {
  44.             i++;
  45.             if (str[i]=='%') {
  46.                 i++;
  47.                 type=2;
  48.             } else if (str[i]=='x') {
  49.                 i++;
  50.                 type=16;
  51.             } else {
  52.                 type=8;
  53.             }
  54.         } else {
  55.             type=10;
  56.         }
  57.     }
  58.     for (;i<strlen(str);i++) {
  59.         c=str[i];
  60.         if (isdigit(c)) {
  61.             n = c - '0';
  62.         } else if (isupper(c)) {
  63.             n = c - 'A' + 10;
  64.         } else if (islower(c)) {
  65.             n = c - 'a' + 10;
  66.         } else {
  67.             goto    out;
  68.         }
  69.         if (n>=type)
  70.             goto out;
  71.         val = (val*type)+n;
  72.     }
  73. out:    
  74.     return(val * sign);
  75. }
  76.