3 ms·
If you want to reinterpret a float as an integer or vice versa, you can do that easily enough with Rust's unsafe functions: fn approx_invsqrt(r : f32) -> f
by JoshTriplett 11y ago
If you want to reinterpret a float as an integer or vice versa, you can do that easily enough with Rust's unsafe functions:
fn approx_invsqrt(r : f32) -> f32
{
let y : f32 = unsafe {
let i : i32 = std::mem::transmute(r);
std::mem::transmute(0x5f375a86 - (i>>1))
};
return y*(1.5-(0.5*r*y*y));
}
fn main()
{
println!("approx_invsqrt(2.0) = {}", approx_invsqrt(2.0));
}
Result:
approx_invsqrt(2.0) = 0.70693
- kzrdude 11y agoAnd Rust specifies their floats to be IEEE 754, so it always works (endianness may apply though).
- JoshTriplett 11y agoSeems reasonably safe to assume that i32 and f32 have the same endianness.