如何在 Rust 中将十六进制字符串转换为浮点数? [英] How to convert hex string to a float in Rust?

查看:110
本文介绍了如何在 Rust 中将十六进制字符串转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将十六进制字符串转换为浮点数的最直接方法是什么?(不使用第 3 方板条箱).

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

Rust 是否提供了一些等效于 Python 的 struct.unpack('!f', bytes.fromhex('41973333'))

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

有关 Python 的问题,请参阅此问题 &Java,提一下供参考.

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

推荐答案

这很容易,无需外部板条箱:

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);
}

游乐场链接.

这篇关于如何在 Rust 中将十六进制字符串转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆