1
0

conv.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * conv.c
  3. */
  4. #include "private.h"
  5. #include <stdlib.h>
  6. #include <errno.h>
  7. #include <limits.h>
  8. /*--------------------------------------------------------- */
  9. int lub_conv_atol(const char *str, long int *val, int base)
  10. {
  11. char *endptr;
  12. long int tmp;
  13. errno = 0;
  14. tmp = strtol(str, &endptr, base);
  15. if ((errno != 0) || (endptr == str))
  16. return -1;
  17. *val = tmp;
  18. return 0;
  19. }
  20. /*--------------------------------------------------------- */
  21. int lub_conv_atoul(const char *str, unsigned long int *val, int base)
  22. {
  23. long int tmp;
  24. if (lub_conv_atol(str, &tmp, base) < 0)
  25. return -1;
  26. if ((tmp < 0) || (tmp > LONG_MAX)) /* Overflow */
  27. return -1;
  28. *val = tmp;
  29. return 0;
  30. }
  31. /*--------------------------------------------------------- */
  32. int lub_conv_atos(const char *str, short *val, int base)
  33. {
  34. long int tmp;
  35. if (lub_conv_atol(str, &tmp, base) < 0)
  36. return -1;
  37. if ((tmp < SHRT_MIN) || (tmp > SHRT_MAX)) /* Overflow */
  38. return -1;
  39. *val = tmp;
  40. return 0;
  41. }
  42. /*--------------------------------------------------------- */
  43. int lub_conv_atous(const char *str, unsigned short *val, int base)
  44. {
  45. unsigned long int tmp;
  46. if (lub_conv_atoul(str, &tmp, base) < 0)
  47. return -1;
  48. if (tmp > USHRT_MAX) /* Overflow */
  49. return -1;
  50. *val = tmp;
  51. return 0;
  52. }
  53. /*--------------------------------------------------------- */
  54. int lub_conv_atoi(const char *str, int *val, int base)
  55. {
  56. long int tmp;
  57. if (lub_conv_atol(str, &tmp, base) < 0)
  58. return -1;
  59. if ((tmp < INT_MIN) || (tmp > INT_MAX)) /* Overflow */
  60. return -1;
  61. *val = tmp;
  62. return 0;
  63. }
  64. /*--------------------------------------------------------- */
  65. int lub_conv_atoui(const char *str, unsigned int *val, int base)
  66. {
  67. unsigned long int tmp;
  68. if (lub_conv_atoul(str, &tmp, base) < 0)
  69. return -1;
  70. if (tmp > UINT_MAX) /* Overflow */
  71. return -1;
  72. *val = tmp;
  73. return 0;
  74. }