fast_atof.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright (C) 2002-2005 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine" and the "irrXML" project.
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h and irrXML.h
  4. #ifndef __FAST_A_TO_F_H_INCLUDED__
  5. #define __FAST_A_TO_F_H_INCLUDED__
  6. #include <stdlib.h>
  7. #include <math.h>
  8. namespace irr
  9. {
  10. namespace core
  11. {
  12. const float fast_atof_table[] = {
  13. 0.f,
  14. 0.1f,
  15. 0.01f,
  16. 0.001f,
  17. 0.0001f,
  18. 0.00001f,
  19. 0.000001f,
  20. 0.0000001f,
  21. 0.00000001f,
  22. 0.000000001f,
  23. 0.0000000001f,
  24. 0.00000000001f,
  25. 0.000000000001f,
  26. 0.0000000000001f,
  27. 0.00000000000001f,
  28. 0.000000000000001f
  29. };
  30. //! Provides a fast function for converting a string into a float,
  31. //! about 6 times faster than atof in win32.
  32. // If you find any bugs, please send them to me, niko (at) irrlicht3d.org.
  33. inline char* fast_atof_move(char* c, float& out)
  34. {
  35. bool inv = false;
  36. char *t;
  37. float f;
  38. if (*c=='-')
  39. {
  40. c++;
  41. inv = true;
  42. }
  43. f = (float)strtol(c, &t, 10);
  44. c = t;
  45. if (*c == '.')
  46. {
  47. c++;
  48. float pl = (float)strtol(c, &t, 10);
  49. pl *= fast_atof_table[t-c];
  50. f += pl;
  51. c = t;
  52. if (*c == 'e')
  53. {
  54. ++c;
  55. float exp = (float)strtol(c, &t, 10);
  56. f *= (float)pow(10.0f, exp);
  57. c = t;
  58. }
  59. }
  60. if (inv)
  61. f *= -1.0f;
  62. out = f;
  63. return c;
  64. }
  65. //! Provides a fast function for converting a string into a float,
  66. //! about 6 times faster than atof in win32.
  67. // If you find any bugs, please send them to me, niko (at) irrlicht3d.org.
  68. inline const char* fast_atof_move_const(const char* c, float& out)
  69. {
  70. bool inv = false;
  71. char *t;
  72. float f;
  73. if (*c=='-')
  74. {
  75. c++;
  76. inv = true;
  77. }
  78. f = (float)strtol(c, &t, 10);
  79. c = t;
  80. if (*c == '.')
  81. {
  82. c++;
  83. float pl = (float)strtol(c, &t, 10);
  84. pl *= fast_atof_table[t-c];
  85. f += pl;
  86. c = t;
  87. if (*c == 'e')
  88. {
  89. ++c;
  90. f32 exp = (f32)strtol(c, &t, 10);
  91. f *= (f32)powf(10.0f, exp);
  92. c = t;
  93. }
  94. }
  95. if (inv)
  96. f *= -1.0f;
  97. out = f;
  98. return c;
  99. }
  100. inline float fast_atof(const char* c)
  101. {
  102. float ret;
  103. fast_atof_move_const(c, ret);
  104. return ret;
  105. }
  106. } // end namespace core
  107. }// end namespace irr
  108. #endif