c++ - Normalized Integer to/from Float Conversion -
i need convert normalized integer values , real floating-point values. instance, int16_t, value of 1.0 represented 32767 , -1.0 represented -32768. although it's bit tedious each integer type, both signed , unsigned, it's still easy enough write hand.
however, want use standard methods whenever possible rather going off , reinventing wheel, i'm looking standard c or c++ header, boost library, or other small, portable, easily-incorporated source performs these conversions.
here's 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 @ 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 , unsigned integers, , 0 normalize 0.