/contrib/ntp/libntp/mstolfp.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 100 lines · 53 code · 13 blank · 34 comment · 19 complexity · 7af31cbb36ad95450a117e960758d7ed MD5 · raw file

  1. /*
  2. * mstolfp - convert an ascii string in milliseconds to an l_fp number
  3. */
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include "ntp_fp.h"
  7. #include "ntp_stdlib.h"
  8. int
  9. mstolfp(
  10. const char *str,
  11. l_fp *lfp
  12. )
  13. {
  14. register const char *cp;
  15. register char *bp;
  16. register const char *cpdec;
  17. char buf[100];
  18. /*
  19. * We understand numbers of the form:
  20. *
  21. * [spaces][-][digits][.][digits][spaces|\n|\0]
  22. *
  23. * This is one enormous hack. Since I didn't feel like
  24. * rewriting the decoding routine for milliseconds, what
  25. * is essentially done here is to make a copy of the string
  26. * with the decimal moved over three places so the seconds
  27. * decoding routine can be used.
  28. */
  29. bp = buf;
  30. cp = str;
  31. while (isspace((int)*cp))
  32. cp++;
  33. if (*cp == '-') {
  34. *bp++ = '-';
  35. cp++;
  36. }
  37. if (*cp != '.' && !isdigit((int)*cp))
  38. return 0;
  39. /*
  40. * Search forward for the decimal point or the end of the string.
  41. */
  42. cpdec = cp;
  43. while (isdigit((int)*cpdec))
  44. cpdec++;
  45. /*
  46. * Found something. If we have more than three digits copy the
  47. * excess over, else insert a leading 0.
  48. */
  49. if ((cpdec - cp) > 3) {
  50. do {
  51. *bp++ = (char)*cp++;
  52. } while ((cpdec - cp) > 3);
  53. } else {
  54. *bp++ = '0';
  55. }
  56. /*
  57. * Stick the decimal in. If we've got less than three digits in
  58. * front of the millisecond decimal we insert the appropriate number
  59. * of zeros.
  60. */
  61. *bp++ = '.';
  62. if ((cpdec - cp) < 3) {
  63. register int i = 3 - (cpdec - cp);
  64. do {
  65. *bp++ = '0';
  66. } while (--i > 0);
  67. }
  68. /*
  69. * Copy the remainder up to the millisecond decimal. If cpdec
  70. * is pointing at a decimal point, copy in the trailing number too.
  71. */
  72. while (cp < cpdec)
  73. *bp++ = (char)*cp++;
  74. if (*cp == '.') {
  75. cp++;
  76. while (isdigit((int)*cp))
  77. *bp++ = (char)*cp++;
  78. }
  79. *bp = '\0';
  80. /*
  81. * Check to make sure the string is properly terminated. If
  82. * so, give the buffer to the decoding routine.
  83. */
  84. if (*cp != '\0' && !isspace((int)*cp))
  85. return 0;
  86. return atolfp(buf, lfp);
  87. }