Search code examples
floating-pointrustieee-754

How to convert float to binary without using unsafe code?


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.


Solution

  • 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);    
    }