uintspec.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*====================================================================*
  2. *
  3. * uint64_t uintspec (char const * string, uint64_t minimum, uint64_t maximum);
  4. *
  5. * number.h
  6. *
  7. * convert a numeric string to an unsigned integer; confirm that
  8. * the result does not exceed the specified range; report errors
  9. * and terminate the program on error;
  10. *
  11. * Motley Tools by Charles Maier;
  12. * Copyright (c) 2001-2006 by Charles Maier Associates;
  13. * Licensed under the Internet Software Consortium License;
  14. *
  15. *--------------------------------------------------------------------*/
  16. #ifndef UINTSPEC_SOURCE
  17. #define UINTSPEC_SOURCE
  18. #include <stdlib.h>
  19. #include <inttypes.h>
  20. #include <ctype.h>
  21. #include <errno.h>
  22. #include "../tools/number.h"
  23. #include "../tools/error.h"
  24. #include "../tools/types.h"
  25. uint64_t uintspec (char const * string, uint64_t minimum, uint64_t maximum)
  26. {
  27. char const * number = string;
  28. unsigned radix = RADIX_DEC;
  29. uint64_t value = 0;
  30. unsigned digit;
  31. if (*number == '0')
  32. {
  33. number++;
  34. if ((*number == 'b') || (*number == 'B'))
  35. {
  36. radix = RADIX_BIN;
  37. number++;
  38. }
  39. else if ((*number == 'x') || (*number == 'X'))
  40. {
  41. radix = RADIX_HEX;
  42. number++;
  43. }
  44. }
  45. while ((digit = todigit (*number)) < radix)
  46. {
  47. value *= radix;
  48. value += digit;
  49. number++;
  50. }
  51. if (*number)
  52. {
  53. error (1, EINVAL, "Have '%s' but want base %d integer", string, radix);
  54. }
  55. if ((value < minimum) || (value > maximum))
  56. {
  57. error (1, ERANGE, "Have %s but want %" PRId64 " thru %" PRId64, string, minimum, maximum);
  58. }
  59. return (value);
  60. }
  61. #endif