home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / PROG_C / SNPD9404.ZIP / HEXORINT.C < prev    next >
C/C++ Source or Header  |  1994-04-03  |  1KB  |  55 lines

  1. /*
  2. **  HEXORINT.C - Detect if a string denotes a hex or decimal
  3. **  number by detecting a leading "0X" or trailing "H" string.
  4. **
  5. **  public domain demo by Bob Stout
  6. */
  7.  
  8. #include <stdlib.h>
  9. #include <string.h>
  10.  
  11. #undef NUL
  12. #define NUL  '\0'
  13.  
  14. #define LAST_CHAR(s) (((char *)s)[strlen(s) - 1])
  15.  
  16. /*
  17. **  Let strtol() do most of the work
  18. */
  19.  
  20. long hexorint(const char *string)
  21. {
  22.       int radix = 0;
  23.       char *dummy, valstr[128];
  24.  
  25.       strcpy(valstr, string);
  26.       if (strchr("Hh", LAST_CHAR(valstr)))
  27.       {
  28.             LAST_CHAR(valstr) = NUL;
  29.             radix = 16;
  30.       }
  31.       return strtol(valstr, &dummy, radix);
  32. }
  33.  
  34. /*
  35. **  Test code follows - compile with TEST macro defined to test
  36. */
  37.  
  38. #ifdef TEST
  39.  
  40. #include <stdio.h>
  41.  
  42. main(int argc, char *argv[])
  43. {
  44.       long val;
  45.  
  46.       while (--argc)
  47.       {
  48.             val = hexorint(*(++argv));
  49.             printf("Value of %s = %ld = %#lx\n", *argv, val, val);
  50.       }
  51.       return EXIT_SUCCESS;
  52. }
  53.  
  54. #endif /* TEST */
  55.