I want to decode, store and encode a float in Rust. I know about num::Float::integer_decode()
but I'd rather not lose any precision. That is, unless the format I encode into is smaller than the format I encode from of course.
Newer versions of Rust provide safer options than some of the other answers suggest:
u64
binary representation.[u8; 8]
. (There are also methods for little-endian byte order and native byte order.)Interpret the floating point bits as an integer and print out the value as hex:
use std::mem;
fn main() {
let a_third: f64 = 1.0 / 3.0;
let as_int: u64 = unsafe { mem::transmute(a_third) };
println!("{}", as_int);
let as_string = format!("{:016x}", as_int);
println!("{}", as_string);
let back_to_int = u64::from_str_radix(&as_string, 16).expect("Not an integer");
println!("{}", back_to_int);
let back_to_float: f64 = unsafe { mem::transmute(back_to_int) };
println!("{}", back_to_float);
assert_eq!(back_to_float, a_third);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With