相关疑难解决方法(0)

解释了将double转换为32位int的快速方法

在阅读Lua的源代码时,我注意到Lua使用a将a macro舍入double到32位int.我解压缩了macro,它看起来像这样:

union i_cast {double d; int i[2]};
#define double2int(i, d, t)  \
    {volatile union i_cast u; u.d = (d) + 6755399441055744.0; \
    (i) = (t)u.i[ENDIANLOC];}
Run Code Online (Sandbox Code Playgroud)

这里ENDIANLOC定义为endianness,0对于little endian,1对于big endian.Lua小心翼翼地处理字节序.t代表整数类型,如intunsigned int.

我做了一些研究,并且有一个更简单的格式macro使用相同的想法:

#define double2int(i, d) \
    {double t = ((d) + 6755399441055744.0); i = *((int *)(&t));}
Run Code Online (Sandbox Code Playgroud)

或者以C++风格:

inline int double2int(double d)
{
    d += 6755399441055744.0;
    return …
Run Code Online (Sandbox Code Playgroud)

c c++ floating-point performance

169
推荐指数
2
解决办法
1万
查看次数

标签 统计

c ×1

c++ ×1

floating-point ×1

performance ×1