在阅读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];}
这里ENDIANLOC定义为endianness,0对于little endian,1对于big endian.Lua小心翼翼地处理字节序.t代表整数类型,如int或unsigned int.
我做了一些研究,并且有一个更简单的格式macro使用相同的想法:
#define double2int(i, d) \
    {double t = ((d) + 6755399441055744.0); i = *((int *)(&t));}
或者以C++风格:
inline int double2int(double d)
{
    d += 6755399441055744.0;
    return …我正在创建一个接收正数的函数,然后将数字四舍五入到它下面最接近的整数.
我一直在使用Math.floor,但最近我发现了Math.trunc.
我知道两者都将返回相同的值,给定一个正数,并且它们以完全不同的方式工作.我有兴趣探索这种行为.