Saving a f32's bits in a usize on a big endian machine


#1

Anyone have an idea if this would work on a big endian machine?

fn main() {
    let a : f32   = 1.7;
    let s : usize = unsafe { *((&a as *const f32) as *const usize) };
    let b : f32   = unsafe { *((&s as *const usize) as *const f32) };
    
    assert_eq!(a, b);
    
    println!("{} {} {}", a, s, b);
}

Or is there some other hidden danger other than “Why the frick are you saving a float in an integer”?. Or is there a better way to do this assignment without a conversion?


#2

The best way to do this sort of conversion is probably to use std::mem::transmute(a) and transmute(s) etc. This should be more reliable because it works with the actual values rather than casting pointers around/relying on their in-memory representation.


#3

Thanks that works and looks safer.