3 ms·
So convert floating point to its integer representation. Would something dirty like this be feasible in rust?
by mkesper 12y ago
So convert floating point to its integer representation.
Would something dirty like this be feasible in rust?
- kaoD 12y agoAFAICT transmute would work: http://rustbyexample.com/staging/unsafe.html http://rustbyexample.com/staging/unsafe.html That's what's great about Rust, you can write unsafe code when you need it and it's isolated in `unsafe` blocks for easy auditing. EDIT: Didn't test it too much, but looks like it works. fn fast_inv_sqrt(x: f32) -> f32 { let f: f32 = unsafe { let i: i32 = std::mem::transmute(x); std::mem::transmute(0x5f3759df - (i >> 1)) }; f * (1.5 - 0.5 * x * f * f) } println!("{}", fast_inv_sqrt(1.0)); //=> 0.998307 println!("{}", fast_inv_sqrt(255.0)); //=> 0.062517 EDIT2: Shorter, more readable version.