Regarding safe float <=> int transmutes

Nice functions to safely transmute float <=> int have being added recently:

https://github.com/rust-lang/rust/pull/39271

You can use them like this:

#![feature(float_bits_conv)]
#![allow(unused_variables)]

fn main() {
    let x1 = 1f32.to_bits();
    let x2 = 1f64.to_bits();

    let y1 = f32::from_bits(0x3f80_0000);
    let y2 = f64::from_bits(0x3ff0_0000_0000_0000);
}

Is it a good idea to add from_bits() to u32/u64, so you can write:

let z1: f32 = 0x3f80_0000u32.from_bits();
let z2: f64 = 0x3ff0_0000_0000_0000u64.from_bits();

f32::from_bits(x)

IMO this is a convenient syntax and it's better. f32 is already “in scope” and the type is up front, not implicit. Since this is a constructor for f32 I think the method fits better there than on the integer types.

I think that 0x3f80_0000.from_bits() with the type inferred from context (the only time you'd save on typing) would be cryptic.

3 Likes