Check bit equiv of f32/f64?

How do I check if two f32 or two f64 are bit equiv? In particular, different NaNs should compare as "not equal"

You can call to_bits() and compare that.

2 Likes

I just reinvented


pub struct F32(pub f32);

pub struct F64(pub f64);

impl F32 {
    #[inline(always)]
    pub fn as_i32_bit(&self) -> i32 {
        let t = &self.0 as &f32 as *const f32 as *const i32;
        unsafe { *t }
    }
}

Is my code above safe? (I'm not sure if I am using unsafe correctly.)

Just call f.to_bits().

2 Likes

Why bother reinventing the wheel?

I reinvented the wheel before reading @cuviper 's suggestion -- and now I am curious if my reinvention is safe or if it results in undefined behaviour.

Your code is sound, and is equivalent to f32::to_bits.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.