How to convert float to binary without using unsafe code?

丶灬走出姿态 提交于 2020-02-03 09:53:41

问题


Is there a way to convert a floating point number (f32 or f64) to a data type that I can access bitwise, like u32/u64? That is, something corresponding to:

fn as_bits(i: f64) -> u64 {
    unsafe { mem::transmute(i) }
}

but without the unsafe. This code is safe per the rules, even though it may not return the same values on all platforms, specifically for NaNs. The reverse safe interface would also be nice.


回答1:


Rust 1.20 introduced f64::to_bits and f32::to_bits:

fn main() {
    println!("{}", (4.2f64).to_bits())
}

Before then, you need to use the unsafe function transmute. They produce the same result:

use std::mem;

fn main() {
    let float = 4.2f64;

    let via_method = float.to_bits();
    let via_transmute: u64 = unsafe { mem::transmute(float) };

    assert_eq!(via_method, via_transmute);    
}


来源:https://stackoverflow.com/questions/44377657/how-to-convert-float-to-binary-without-using-unsafe-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!