FloatIntConversion.hpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* Copyright 2025, Ableton AG, Berlin. All rights reserved.
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. * If you would like to incorporate Link into a proprietary software application,
  17. * please contact <link-devs@ableton.com>.
  18. */
  19. #pragma once
  20. #include <algorithm>
  21. #include <cmath>
  22. #include <cstdint>
  23. #include <limits>
  24. namespace ableton
  25. {
  26. namespace util
  27. {
  28. template <typename T>
  29. int16_t floatToInt16(const T src)
  30. {
  31. static_assert(std::is_same<T, float>::value || std::is_same<T, double>::value);
  32. constexpr auto kScale = std::numeric_limits<int16_t>::max() + 1;
  33. constexpr auto kMin = T{-1};
  34. constexpr auto kMax = T{1} - T{1} / kScale;
  35. return int16_t(std::round(kScale * std::clamp(src, kMin, kMax)));
  36. }
  37. template <typename T>
  38. T int16ToFloat(const int16_t src)
  39. {
  40. static_assert(std::is_same<T, float>::value || std::is_same<T, double>::value);
  41. constexpr auto kScale = std::numeric_limits<int16_t>::max() + 1;
  42. return static_cast<T>(src) / kScale;
  43. }
  44. } // namespace util
  45. } // namespace ableton