uintspec.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 <cmaier@cmassoc.net>;
  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 need base %d integer %" PRId64 " thru %" PRId64, string, radix, minimum, maximum);
  54. }
  55. if ((value < minimum) || (value > maximum))
  56. {
  57. error (1, EINVAL, "Have '%s' but need %" PRId64 " thru %" PRId64, string, minimum, maximum);
  58. }
  59. return (value);
  60. }
  61. #endif