归一化到/从浮点数转换整数 [英] Normalized Integer to/from Float Conversion

查看:692
本文介绍了归一化到/从浮点数转换整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将标准化的整数值转换为实际的浮点值和从实际的浮点值转换。例如,对于int16_t,1.0的值由32767表示,-1.0由-32768表示。尽管对每个整数类型(有符号和无符号)做这个操作有点繁琐,但手动编写仍然很容易。

然而,我想使用标准方法只要有可能,而不是重新发明轮子,那么我要找的东西就像是一个标准的C或C ++头文件,一个Boost库,或者其他一些已经执行了这些转换的小巧,便携,易于合并的源代码。 / p>

解决方案

这是一个使用 std :: numeric_limits 的模板化解决方案:

  #include< cstdint> 
#include< limits>

模板< typename T>
constexpr double normalize(T value){
返回值< 0
? -static_cast< double>(value)/ std :: numeric_limits< T> :: min()
:static_cast< double>(value)/ std :: numeric_limits< T> :: max ;
}

int main(){
//测试用例在编译时计算。
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,);



$ b

这个处理有符号整数和无符号整数,0标准化为0。 / p>

查看成功的编辑结果

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.

解决方案

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

这篇关于归一化到/从浮点数转换整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆