我已经知道如何使用截断实现到半精度浮点的转换(感谢 this answer )。但是如何使用最近可表示的四舍五入进行相同的转换?例如,我希望 65519 舍入为 0x7bff(即 65504),而不是无穷大。再举一个例子:在链接的解决方案中,8199 将用 8192 表示,但 8199 可表示的最接近的是 8200
更新:更多示例案例:我想将 32768 和 65519 之间的整数舍入为 32 的倍数,将 16384 和 32768 之间的整数舍入为 16 的倍数,依此类推。在此解决方案中,8199 将由 8192 表示,但最接近的 8199 可表示为 8200
最佳答案
你需要两部分来实现你想要的。
1. 在进行转换之前添加舍入
通过添加:
// round the number if necessary before we do the conversion
if (manbits > 13)
absx += (2<<(manbits-13));
manbits = 0;
tmp = absx;
while (tmp)
{
tmp >>= 1;
manbits++;
}
在您进行转换之前。
2. 将裁剪为 infinty 更改为
> 16
通过改变
if (exp + truncated > 15)
到:
if (exp + truncated > 16)
我更新了原代码https://ideone.com/mWqgSP
关于使用舍入到偶数将整数转换为半精度浮点格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381846/