简体   繁体   English

将浮点数转换为无符号整数C ++

[英]convert floats into unsigned ints c++

How can I convert or scale floating point numbers into unsigned ints. 如何将浮点数转换或缩放为无符号整数。

I have a floating point vector whose min and max are known, let's say -10 to +10 and I want convert these into unsigned integers from 0 to int_max. 我有一个浮点向量,其最小值和最大值是已知的,例如-10到+10,我想将它们转换为从0到int_max的无符号整数。

Simply calculate where exactly in the float interval the float value is (as a 0-1 value; you can also think of it as percent). 只需简单地计算出浮动间隔在浮动间隔中的确切位置(即0-1值;您也可以将其视为百分比)。 Then scale the max integer value accordingly. 然后相应地缩放最大整数值。 In code: 在代码中:

const float minFloat = -10.f;
const float maxFloat = 10.f;
const unsigned int maxInt = std::numeric_limits<int>::max(); // Is that what you wanted?

unsigned int convert(float val)
{
  val = (val - minFloat) / (maxFloat - minFloat);
  return static_cast<unsigned int>(std::round(val * maxInt));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM