I wanted to print the hexadecimal representation of an f32 in Rust. I searched for a while for the correct way to do this but didn't find anything. I found evidence that functions to convert f32 and f64 to hex used to exist in the Rust standard library but got removed at some point before Rust 1.0 was released. So I had to resort to unsafe Rust. It seems like there should be a better way but this works.
let f = 1.0f32;
//println!("{:x}", f); // compile error, this doesn't work
println!("{:x}", unsafe { std::mem::transmute::<f32, u32>(f) }); // outputs "3f800000" as expected
Update October 2017: Rust 1.21.0 now has stabilized the
to_bits method on f32's. No more unsafe calls needed.
No comments:
Post a Comment