我需要将存储的半浮点数(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
}
}
答案 0 :(得分:4)
您只需将ffi::c_ldexpf(x, y)
替换为x * (2.0).powi(y)
即可。根据{{3}},这适用于所有u16
。