What is the fastest way to convert float to int on x86

前端 未结 10 2254
轻奢々
轻奢々 2020-11-28 11:26

What is the fastest way you know to convert a floating-point number to an int on an x86 CPU. Preferrably in C or assembly (that can be in-lined in C) for any combination of

10条回答
  •  心在旅途
    2020-11-28 11:56

    A commonly used trick for plain x86/x87 code is to force the mantissa part of the float to represent the int. 32 bit version follows.

    The 64-bit version is analogical. The Lua version posted above is faster, but relies on the truncation of double to a 32-bit result, therefore it requires the x87 unit to be set to double precision, and cannot be adapted for double to 64-bit int conversion.

    The nice thing about this code is it is completely portable for all platforms conforming to IEEE 754, the only assumption made is the floating point rounding mode is set to nearest. Note: Portable in the sense it compiles and works. Platforms other than x86 usually do not benefit much from this technique, if at all.

    static const float Snapper=3<<22;
    
    union UFloatInt {
     int i;
     float f;
    };
    
    /** by Vlad Kaipetsky
    portable assuming FP24 set to nearest rounding mode
    efficient on x86 platform
    */
    inline int toInt( float fval )
    {
      Assert( fabs(fval)<=0x003fffff ); // only 23 bit values handled
      UFloatInt &fi = *(UFloatInt *)&fval;
      fi.f += Snapper;
      return ( (fi.i)&0x007fffff ) - 0x00400000;
    }
    

提交回复
热议问题