Search code examples
rustcasting

How can I cast between f32 and u32 without changing the bits?


So i'm making a virtual machine which takes in a sequence of 32 bits (so multiple batches of 32 bits) and they're represented as u32s, but in reality the number could be a f32 but just wrapped in a u32. My program knows when a u32 actually represents a f32, but I'm not sure how to convert them. If I used as would it do rounding or would it just shove the bits between the formats (I want the latter)? Because what I want is to convert between u32 and f32 without changing any of the underlying bits, I just want to call it a different thing. Here for example I'm worried that my as u32 won't be doing what I want it to be doing:

pub fn give_velocity(spell: &mut Spell, parameters: &[u32], should_execute: bool) -> Option<u32> {
    match should_execute {
        true => Some((spell.energy * sqrt((parameters[0] * parameters[0] + parameters[1] * parameters[1] + parameters[2] * parameters[2]) as f64)) as u32),
        false => None
    }
}

Also ignore the fact that should_execute is useless right now, it's not finished.

Edit: My question has been answered for how to convert f32 to u32 but what about u32 to f32?


Solution

  • To get the underlying bits of an f32 value as a u32, use f32::to_bits. To do the reverse, use f32::from_bits(_):

    fn main() {
        let value: f32 = 1.23;
        let u32 = value.to_bits();
        println!("{}, {}", value, u32);
        assert_eq!(value, f32::from_bits(u32));
    }
    

    Output:

    1.23, 1067282596