简体   繁体   中英

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.

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). 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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