Inspect a float's raw bits in Rust with f32::to_bits
Read the raw IEEE 754 bits of an f32 in Rust with to_bits, and rebuild a float from bits with from_bits, instead of reaching for unsafe transmute.
f32::to_bits returns the 32 bits of a float as a u32, and f32::from_bits goes the other way. Both are safe, so there is no reason to use transmute or a union to look at a float's layout.
fn main() {
println!("{:#010x}", 1.0_f32.to_bits());
println!("{:#010x}", (-2.5_f32).to_bits());
println!("{:#010x}", f32::INFINITY.to_bits());
println!("{}", f32::from_bits(0x3f80_0000));
let bits = (-2.5_f32).to_bits();
println!("sign {} exp {} frac {:#x}", bits >> 31, (bits >> 23) & 0xFF, bits & 0x7F_FFFF);
}0x3f800000
0xc0200000
0x7f800000
1
sign 1 exp 128 frac 0x200000For -2.5 the sign bit is 1, the biased exponent is 128 (which means 2^1, since the bias is 127), and the fraction is 0x200000, the bits of 0.25, giving 1.25 times 2 and a minus sign. The bit pattern of a NaN is not fixed by the language, so do not print or compare f32::NAN.to_bits() and expect it to be the same on every target. to_bits is the correct way to compare floats exactly, to hash them, or to sort them with total_cmp semantics. See the f32 documentation. The f64 pair works the same way with u64.