inline int floatToUInt(float x)
    unsigned int e = (0x7F + 31) - ((* (unsigned int*) &x & 0x7F800000) >> 23);
    unsigned int m = 0x80000000 | (* (unsigned int*) &x << 8);
    return int((m >> e) & -(e < 32));

inline int roundToIntFloat(float x)
    // round
    if (x >= 0)
        return floatToUInt(x + 0.5f);
    return -floatToUInt(0.5f - x);

// specialise
template <>
inline int roundToInt<float>(const float value) noexcept
    return roundToIntFloat(value);

Been trying it in my builds, mainly to avoid unnecessary use of double.



Isn't there juce::roundFloatToInt() that does that job already?

Edit: Though I'm not sure if the result is the same with what you did and what juce does with .5 values.


So is that equivalent but faster? I vaguely remember seeing where someone had benchmarked all the float->int techniques and found that on newer CPUs it's better just to do it with a cast..

BTW got to be careful with that old "* (unsigned int*) &x" trick - it produces broken code on some compilers with optimisations enabled, so best to always use a union instead.


std::trunc(), anyone?





Blimey, I don't remember now.. I just vaguely remember changing it a while ago for some reason - I think because I read some benchmarks or something..