0

I have a positive float array and would like to convert this array to an unsigned short array with rounding. How can I do that in an efficient way? Here is an example:

float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
unsigned short usArr[5];
// I could do this
std::copy(floatArr, 5, usArr);

However, it will only do the casting, since it basically copies the first two bytes. So the result is usArr[] = {1, 1, 2, 2, 3}. My question is how can I convert this float array with rounding, instead of casting, to be usArr[] = {1, 2, 2, 3, 3}? Thank you and I would appreciate any help!

3
  • You can add 0.5 to each value before converting. That will make the rounding work correctly. Commented Jan 22, 2016 at 21:22
  • @Baldrick I just thought about that! Yeah, that's the solution. Thank you! Appreciated! Commented Jan 22, 2016 at 21:25
  • @JosephJohns - floor isn't needed here. Assignment to an integral type does that. Commented Jan 22, 2016 at 21:47

1 Answer 1

3

It seems that you want to round to nearest instead of rounding down std::round will help you with this. Use std::transform to do rounding and copying in one step:

#include <algorithm>
#include <iostream>
#include <cmath>

int main()  
{
    float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
    unsigned short usArr[5];

    // (1) Using a lambda to choose correct overload:
    std::transform(floatArr, floatArr + 5, usArr, [](float f){ return std::round(f); });

    // (2) Using static cast to enforce that specific overload is called:
    std::transform(floatArr, floatArr + 5, usArr, static_cast<float(*)(float)>(std::round));

    for(int i = 0; i < 5; ++i)
        std::cout << usArr[i] << ' ';
 }
Sign up to request clarification or add additional context in comments.

6 Comments

This is awesome! I never used 'std::transform()' before. It works really well. Thank you!
That's great. Better than my suggestion in the comment. I still think like a C programmer sometimes... :)
That type conversion is a bit fishy.
@Peter It is here to resolve ambiguity in which overloaded function should be chosen. You can wrap it in lambda instead.
You've resolved the ambiguity in a way that calls a double (*) (double) as if it is a float (*)(float). That gives undefined behaviour. A lambda would be better.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.