strtoll.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #define VLONG_MAX ~(1LL<<63)
  12. #define VLONG_MIN (1LL<<63)
  13. int64_t
  14. <<<<<<< HEAD
  15. strtoll(char *nptr, char **endptr, int base)
  16. =======
  17. strtoll(const char *nptr, char **endptr, int base)
  18. >>>>>>> 064e99309... Changed strto[l|ul|ull] functions to have correct signature
  19. {
  20. char *p;
  21. int64_t n, nn, m;
  22. int c, ovfl, v, neg, ndig;
  23. p = nptr;
  24. neg = 0;
  25. n = 0;
  26. ndig = 0;
  27. ovfl = 0;
  28. /*
  29. * White space
  30. */
  31. for(;; p++) {
  32. switch(*p) {
  33. case ' ':
  34. case '\t':
  35. case '\n':
  36. case '\f':
  37. case '\r':
  38. case '\v':
  39. continue;
  40. }
  41. break;
  42. }
  43. /*
  44. * Sign
  45. */
  46. if(*p=='-' || *p=='+')
  47. if(*p++ == '-')
  48. neg = 1;
  49. /*
  50. * Base
  51. */
  52. if(base==0){
  53. base = 10;
  54. if(*p == '0') {
  55. base = 8;
  56. if(p[1]=='x' || p[1]=='X') {
  57. p += 2;
  58. base = 16;
  59. }
  60. }
  61. } else
  62. if(base==16 && *p=='0') {
  63. if(p[1]=='x' || p[1]=='X')
  64. p += 2;
  65. } else
  66. if(base<0 || 36<base)
  67. goto Return;
  68. /*
  69. * Non-empty sequence of digits
  70. */
  71. m = VLONG_MAX/base;
  72. for(;; p++,ndig++) {
  73. c = *p;
  74. v = base;
  75. if('0'<=c && c<='9')
  76. v = c - '0';
  77. else
  78. if('a'<=c && c<='z')
  79. v = c - 'a' + 10;
  80. else
  81. if('A'<=c && c<='Z')
  82. v = c - 'A' + 10;
  83. if(v >= base)
  84. break;
  85. if(n > m)
  86. ovfl = 1;
  87. nn = n*base + v;
  88. if(nn < n)
  89. ovfl = 1;
  90. n = nn;
  91. }
  92. Return:
  93. if(ndig == 0)
  94. p = nptr;
  95. if(endptr)
  96. *endptr = (char *)p;
  97. if(ovfl){
  98. if(neg)
  99. return VLONG_MIN;
  100. return VLONG_MAX;
  101. }
  102. if(neg)
  103. return -n;
  104. return n;
  105. }