How do you cast a u32 to an f32 in rust?

104 points fengli

How do you cast a u32 (that contains f32 data) to be treated as an f32 inside rust?

In golang, this is done using unsafe, can it be done in rust without using unsafe:

func Float32frombits(b uint32) float32 {
    return *(*float32)(unsafe.Pointer(&b))
}

https://cs.opensource.google/go/go/+/refs/tags/go1.22.2:src/math/unsafe.go;l=18

(To be super clear, this is not a conversion of a number like 1000 inside a u32 to 1000 as f32. This is conversion of the data contained in the four bytes the u32 to an f32 value.)