Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert hex string to a f64 in Rust?

Based on the following question:

How to convert hex string to a float in Rust?

I’ve tried the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading