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.

view successful compilation result


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo