FloatTraits.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright Benoit Blanchon 2014-2017
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://bblanchon.github.io/ArduinoJson/
  6. // If you like this project, please add a star!
  7. #pragma once
  8. #include <stdint.h>
  9. #include <stdlib.h> // for size_t
  10. #include "../Polyfills/math.hpp"
  11. namespace ArduinoJson {
  12. namespace TypeTraits {
  13. template <typename T, size_t = sizeof(T)>
  14. struct FloatTraits {};
  15. #ifndef ARDUINO_ARCH_AVR // double is 32 bits, so 1e64 gives a warning
  16. template <typename T>
  17. struct FloatTraits<T, 8 /*64bits*/> {
  18. typedef int64_t mantissa_type;
  19. static const short mantissa_bits = 52;
  20. static const mantissa_type mantissa_max =
  21. (static_cast<mantissa_type>(1) << mantissa_bits) - 1;
  22. typedef int16_t exponent_type;
  23. static const exponent_type exponent_max = 308;
  24. template <typename TExponent>
  25. static T make_float(T m, TExponent e) {
  26. if (e >= 0)
  27. return m * (e & 1 ? 1e1 : 1) * (e & 2 ? 1e2 : 1) * (e & 4 ? 1e4 : 1) *
  28. (e & 8 ? 1e8 : 1) * (e & 16 ? 1e16 : 1) * (e & 32 ? 1e32 : 1) *
  29. (e & 64 ? 1e64 : 1) * (e & 128 ? 1e128 : 1) *
  30. (e & 256 ? 1e256 : 1);
  31. e = -e;
  32. return m * (e & 1 ? 1e-1 : 1) * (e & 2 ? 1e-2 : 1) * (e & 4 ? 1e-4 : 1) *
  33. (e & 8 ? 1e-8 : 1) * (e & 16 ? 1e-16 : 1) * (e & 32 ? 1e-32 : 1) *
  34. (e & 64 ? 1e-64 : 1) * (e & 128 ? 1e-128 : 1) *
  35. (e & 256 ? 1e-256 : 1);
  36. }
  37. static T nan() {
  38. return Polyfills::nan<T>();
  39. }
  40. static T inf() {
  41. return Polyfills::inf<T>();
  42. }
  43. };
  44. #endif
  45. template <typename T>
  46. struct FloatTraits<T, 4 /*32bits*/> {
  47. typedef int32_t mantissa_type;
  48. static const short mantissa_bits = 23;
  49. static const mantissa_type mantissa_max =
  50. (static_cast<mantissa_type>(1) << mantissa_bits) - 1;
  51. typedef int8_t exponent_type;
  52. static const exponent_type exponent_max = 38;
  53. template <typename TExponent>
  54. static T make_float(T m, TExponent e) {
  55. if (e > 0)
  56. return m * (e & 1 ? 1e1f : 1) * (e & 2 ? 1e2f : 1) * (e & 4 ? 1e4f : 1) *
  57. (e & 8 ? 1e8f : 1) * (e & 16 ? 1e16f : 1) * (e & 32 ? 1e32f : 1);
  58. e = -e;
  59. return m * (e & 1 ? 1e-1f : 1) * (e & 2 ? 1e-2f : 1) * (e & 4 ? 1e-4f : 1) *
  60. (e & 8 ? 1e-8f : 1) * (e & 16 ? 1e-16f : 1) * (e & 32 ? 1e-32f : 1);
  61. }
  62. static T nan() {
  63. return Polyfills::nan<T>();
  64. }
  65. static T inf() {
  66. return Polyfills::inf<T>();
  67. }
  68. };
  69. }
  70. }