Normalized Integer to/from Float Conversion

喜你入骨 提交于 2019-12-23 12:24:30

问题


I need to convert normalized integer values to and from real floating-point values. For instance, for int16_t, a value of 1.0 is represented by 32767 and -1.0 is represented by -32768. Although it's a bit tedious to do this for each integer type, both signed and unsigned, it's still easy enough to write by hand.

However, I want to use standard methods whenever possible rather than going off and reinventing the wheel, so what I'm looking for is something like a standard C or C++ header, a Boost library, or some other small, portable, easily-incorporated source that already performs these conversions.


回答1:


Here's a templated solution using std::numeric_limits:

#include <cstdint>
#include <limits>

template <typename T>
constexpr double normalize (T value) {
  return value < 0
    ? -static_cast<double>(value) / std::numeric_limits<T>::min()
    :  static_cast<double>(value) / std::numeric_limits<T>::max()
    ;
}

int main () {
  // Test cases evaluated at compile time.
  static_assert(normalize(int16_t(32767)) == 1, "");
  static_assert(normalize(int16_t(0)) == 0, "");
  static_assert(normalize(int16_t(-32768)) == -1, "");
  static_assert(normalize(int16_t(-16384)) == -0.5, "");
  static_assert(normalize(uint16_t(65535)) == 1, "");
  static_assert(normalize(uint16_t(0)) == 0, "");
}

This handles both signed and unsigned integers, and 0 does normalize to 0.

View Successful Compilation Result




回答2:


Although it's a bit tedious to do this for each integer type, both signed and unsigned, it's still easy enough to write by hand.

You certainly don't need to do this for each integer type! Use <limits> instead.

template<class T> double AsDouble(const T x) {
    const double valMin = std::numeric_limits<T>::min();
    const double valMax = std::numeric_limits<T>::max();
    return 2 * (x - valMin) / (valMax - valMin) - 1; // note: 0 does not become 0.
}


来源:https://stackoverflow.com/questions/37580501/normalized-integer-to-from-float-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!