0

Based on the following question:

How to convert hex string to a float in Rust?

I've tried the following code:

fn main() {
    // Hex string to 8 bytes, aka. u64
    let bytes = u64::from_str_radix("c51981cb", 16).unwrap();

    // Reinterpret 8 bytes as f64:
    let float = unsafe { std::mem::transmute::<u64, f64>(bytes) };
    println!("float: {}", float);
}

This compiles and runs, but according to https://www.h-schmidt.net/FloatConverter/IEEE754.html, the answer should be -2456.11206055, rather than the 0.000.... number I'm getting.

Have I got a problem with BE/LE? Or am I making some other mistake?

DobbyTheElf
  • 604
  • 6
  • 21
  • Why not try encoding to hex, and then decoding a known-good value? What you have there looks short for a u64. – tadman Jul 23 '23 at 18:17
  • 2
    You can avoid the transmute (and unsafe code altogether) with [`f64::from_bits()`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.from_bits). – Chayim Friedman Jul 23 '23 at 18:26

1 Answers1

5

The calculator you linked is for single precision floating point values, but your code assumed double precision floating points, and indeed converting to u32 and f32 the single precision floating point type gives the expected result:

fn main() {
    // Hex string to 4 bytes, aka. u32
    let bits = u32::from_str_radix("c51981cb", 16).unwrap();
    // Reinterpret 4 bytes as f32:
    let float = f32::from_bits(bits);
    println!("float: {float:.8}"); //float: -2456.11206055
}
cafce25
  • 15,907
  • 4
  • 25
  • 31