如何仅使用稳定的标准库将 f16 解码为 f32?

How can I decode f16 to f32 using only the stable standard library?

我需要将存储的半浮点数(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
    }
}

您可以将 ffi::c_ldexpf(x, y) 替换为 x * (2.0).powi(y)。根据 my exhaustive test.

,这适用于所有 u16s