【问题标题】:How can I decode f16 to f32 using only the stable standard library?如何仅使用稳定的标准库将 f16 解码为 f32?
【发布时间】:2016-03-15 10:18:55
【问题描述】:

我需要将存储的半浮点数(16 位)转换为标准的 32 位浮点数。我目前使用下面的代码,但它依赖于 libc。我只想使用 std,它应该可以在稳定的 Rust 上工作。

#[inline]
fn decode_f16(half: u16) -> f32 {
    let exp: u16 = half >> 10 & 0x1f;
    let mant: u16 = half & 0x3ff;
    let val: f32 = if exp == 0 {
        ffi::c_ldexpf(mant as f32, -24)
    } else if exp != 31 {
        ffi::c_ldexpf(mant as f32 + 1024f32, exp as isize - 25)
    } else if mant == 0 {
        ::std::f32::INFINITY
    } else {
        ::std::f32::NAN
    };
    if half & 0x8000 != 0 {
        -val
    } else {
        val
    }
}

【问题讨论】:

标签: floating-point rust precision


【解决方案1】:

您可以将ffi::c_ldexpf(x, y) 替换为x * (2.0).powi(y)。根据my exhaustive test,这适用于所有u16s。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 2012-07-23
    • 2021-08-29
    • 1970-01-01
    • 2021-02-10
    • 2019-06-08
    • 2020-10-12
    相关资源
    最近更新 更多