Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalized Integer to/from Float Conversion

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.

like image 983
IntellectualKitty Avatar asked Jun 01 '16 23:06

IntellectualKitty


1 Answers

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

like image 150
Binary Birch Tree Avatar answered Sep 18 '22 14:09

Binary Birch Tree