2

What's the most straightforward way to convert a hex string into a float? (without using 3rd party crates).

Does Rust provide some equivalent to Python's struct.unpack('!f', bytes.fromhex('41973333'))


See this question for Python & Java, mentioning for reference.

2
  • 4
    Why do you stick without crates? Commented Apr 30, 2017 at 9:50
  • Since this can be done in a few lines in other languages, I'd like to know how to do primitive operations without introducing middle-ware. Commented Apr 30, 2017 at 9:51

2 Answers 2

5

This is quite easy without external crates:

fn main() {
    // Hex string to 4-bytes, aka. u32
    let bytes = u32::from_str_radix("41973333", 16).unwrap();

    // Reinterpret 4-bytes as f32:
    let float = unsafe { std::mem::transmute::<u32, f32>(bytes) };

    // Print 18.9
    println!("{}", float);
}

Playground link.

Sign up to request clarification or add additional context in comments.

Comments

5

There's f32::from_bits which performs the transmute in safe code. Note that transmuting is not the same as struct.unpack, since struct.unpack lets you specify endianness and has a well-defined IEEE representation.

3 Comments

The endianness issue can easily be dealt with with {from,to}_{be,le}. f32::from_bits also has the advantage to deal with NaN values correctly.
@mcarton It's not entirely certain that from_bits handles NaN more correctly; it's just more conservative. Whether signalling NaNs can actually cause unsafe behaviour is still under debate.
@mcarton from_bits is now exactly equivalent to a transmute. github.com/rust-lang/rust/pull/46012

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.