40 lines
1.1 KiB
Markdown
40 lines
1.1 KiB
Markdown
|
# round/floor a f32 using logical operations and integer arithmetical operations in Rust
|
||
|
|
||
|
Yith this function you can able to truncate a float f32 using bitwise, logical operations and integer arithmetical operation.
|
||
|
The function has not 100% of precisition because ignore most of the bits in the mantissa, but it's often to round small numbers.
|
||
|
|
||
|
```Rust
|
||
|
fn round(mut f: f32) -> i32 {
|
||
|
let sign = f < 0.0;
|
||
|
if sign {
|
||
|
f = f * -1.0;
|
||
|
}
|
||
|
|
||
|
let digits = f.to_bits();
|
||
|
|
||
|
let mut exponent = (digits as i32 >> 23) & (!(1 << 8));
|
||
|
let mantissa = (digits - (digits >> 23 << 23)) >> 16 | 1 << 7;
|
||
|
|
||
|
exponent -= 127;
|
||
|
|
||
|
if exponent < 0 {
|
||
|
return 0;
|
||
|
}
|
||
|
let exponent: u32 = 1 << exponent as u32;
|
||
|
|
||
|
let mut result: i32 = (exponent * mantissa) as i32 / 128;
|
||
|
if sign {
|
||
|
result *= -1;
|
||
|
}
|
||
|
result
|
||
|
}
|
||
|
|
||
|
fn main() {
|
||
|
println!("{}", round(15.125));
|
||
|
println!("{}", round(14.345));
|
||
|
println!("{}", round(-1.555));
|
||
|
println!("{}", round(-9.001));
|
||
|
println!("{}", round(-999.001));
|
||
|
println!("{}", round(-0.5));
|
||
|
}
|
||
|
```
|