Float Bits Roundtrip Exact

Round-trip floats through f64::to_bits and from_bits to preserve negative zero and NaN payloads that ordinary equality cannot check.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    let values = [0.1_f64, -0.0, f64::INFINITY, f64::from_bits(0x7ff8_0000_0000_0001)];

    for value in values {
        // to_bits keeps every bit of the float, including the NaN payload
        let bits = value.to_bits();
        let restored = f64::from_bits(bits);
        println!("{bits:#018x} bits stable: {}", bits == restored.to_bits());
    }

    // negative zero and positive zero compare equal by value but differ by bits
    println!("neg zero bits: {:#018x}", (-0.0_f64).to_bits());
    println!("value equal: {}", (-0.0_f64) == 0.0);

    // NaN never equals itself, so identity has to go through the bit pattern
    let nan = f64::from_bits(0x7ff8_0000_0000_0001);
    println!("nan equals itself: {}", nan == nan);
    println!("nan bits stable: {}", nan.to_bits() == 0x7ff8_0000_0000_0001);
}

Inside the snippet

Float Bits Roundtrip Exact is built around the function main.

Iteration happens inside for value in values — everything outside it runs once.

Points of care

  • No package manager involved — every call resolves to a built-in API.

Putting it to use

The main signature reads fn main()

The run emits 3 labeled sections — neg zero bits:, value equal:, nan equals itself: — one per step.

Core lines

let values = [0.1_f64, -0.0, f64::INFINITY, f64::from_bits(0x7ff8_0000_0000_0001)];
let nan = f64::from_bits(0x7ff8_0000_0000_0001);
let restored = f64::from_bits(bits);

Interactive Tools for This Topic

FAQ

What does Float Bits Roundtrip Exact print when run?
The script runs standalone; its 4 labeled outputs include `neg zero bits:`, `value equal:`, `nan equals itself:`.