hexfloat.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // Define a hexfloat literal emulator since we can't depend on being able to
  9. // for hexfloat literals
  10. // 0x10.F5p-10 == hexfloat<double>(0x10, 0xF5, -10)
  11. #ifndef HEXFLOAT_H
  12. #define HEXFLOAT_H
  13. #include <cmath>
  14. #include <climits>
  15. template <class T>
  16. class hexfloat
  17. {
  18. T value_;
  19. static int CountLeadingZeros(unsigned long long n) {
  20. const std::size_t Digits = sizeof(unsigned long long) * CHAR_BIT;
  21. const unsigned long long TopBit = 1ull << (Digits - 1);
  22. if (n == 0) return Digits;
  23. int LeadingZeros = 0;
  24. while ((n & TopBit) == 0) {
  25. ++LeadingZeros;
  26. n <<= 1;
  27. }
  28. return LeadingZeros;
  29. }
  30. public:
  31. hexfloat(long long m1, unsigned long long m0, int exp)
  32. {
  33. const std::size_t Digits = sizeof(unsigned long long) * CHAR_BIT;
  34. int s = m1 < 0 ? -1 : 1;
  35. int exp2 = -static_cast<int>(Digits - CountLeadingZeros(m0)/4*4);
  36. value_ = std::ldexp(m1 + s * std::ldexp(T(m0), exp2), exp);
  37. }
  38. operator T() const {return value_;}
  39. };
  40. #endif