Created
August 3, 2021 17:31
-
-
Save 0xpantera/aa2ab7240219f04ada430b4185cd6df6 to your computer and use it in GitHub Desktop.
42.42 es el f32 que estoy desarmando
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BIAS: i32 = 127; | |
const RADIX: f32 = 2.0; | |
fn main() { | |
let n: f32 = 42.42; | |
let (sign, exp, frac) = to_parts(n); | |
let (sign_, exp_, mant) = decode(sign, exp, frac); | |
let n_ = from_parts(sign_, exp_, mant); | |
println!("{} -> {}", n, n_); | |
println!("field | as bits | as real number"); | |
println!("sign | {:01b} | {}", sign, sign_); | |
println!("exponent | {:08b} | {}", exp, exp_); | |
println!("mantissa | {:023b} | {}", frac, mant); | |
} | |
fn to_parts(n: f32) -> (u32, u32, u32) { | |
let bits = n.to_bits(); | |
let sign = (bits >> 31) & 1; | |
let exponent = (bits >> 23) & 0xff; | |
let fraction = bits & 0x7fffff; | |
(sign, exponent, fraction) | |
} | |
fn decode(sign: u32, exponent: u32, fraction: u32) -> (f32, f32, f32) { | |
let signed_1 = (-1.0_f32).powf(sign as f32); | |
let mut mantissa: f32 = 1.0; | |
let exponent = (exponent as i32) - BIAS; | |
let exponent = RADIX.powf(exponent as f32); | |
for i in 0..23 { | |
let mask = 1 << i; | |
let one_at_bit_i = fraction & mask; | |
if one_at_bit_i != 0 { | |
let i_ = i as f32; | |
let weight = 2_f32.powf(i_ - 23.0); | |
mantissa += weight; | |
} | |
} | |
(signed_1, exponent, mantissa) | |
} | |
fn from_parts(sign: f32, exponent: f32, mantissa: f32) -> f32 { | |
sign * exponent * mantissa | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment