Normalized Integer to/from Float Conversion
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