如何将float转换为二进制而不使用不安全的代码? [英] How to convert float to binary without using unsafe code?

查看:445
本文介绍了如何将float转换为二进制而不使用不安全的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将一个浮点数( f32 f64 )转换为一个数据类型I可以按位访问,如 u32 / u64 ?也就是说,对应于:

  fn as_bits(i:f64) - > u64 {
unsafe {mem :: transmute(i)}
}

但没有不安全。此代码根据规则是安全的,即使它可能不会在所有平台上返回相同的值,特别是对于NaN。反向安全的接口也不错。

解决方案

Nightly Rust有 float_bits_conv 启用 f64 :: to_bits

 <$ c   ($ {$ $',(4.2f64).to_bits())
} $ {$ b $ $ $ $ $ $'

在该特性稳定之前(看起来在Rust 1.20中),需要使用不安全函数 transmute 。它们产生相同的结果:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ MEM;

fn main(){
let float = 4.2f64;

let via_method = float.to_bits();
让via_transmute:u64 = unsafe {mem :: transmute(float)};

assert_eq!(via_method,via_transmute);
}


Is there a way to convert a floating point number (f32 or f64) to a data type that I can access bitwise, like u32/u64? That is, something corresponding to:

fn as_bits(i: f64) -> u64 {
    unsafe { mem::transmute(i) }
}

but without the unsafe. This code is safe per the rules, even though it may not return the same values on all platforms, specifically for NaNs. The reverse safe interface would also be nice.

解决方案

Nightly Rust has the float_bits_conv feature which enables f64::to_bits and f32::to_bits, among other methods:

#![feature(float_bits_conv)]

fn main() {
    println!("{}", (4.2f64).to_bits())
}

Before that feature is stabilized (which looks to be in Rust 1.20), you need to use the unsafe function transmute. They produce the same result:

#![feature(float_bits_conv)]

use std::mem;

fn main() {
    let float = 4.2f64;

    let via_method = float.to_bits();
    let via_transmute: u64 = unsafe { mem::transmute(float) };

    assert_eq!(via_method, via_transmute);    
}

这篇关于如何将float转换为二进制而不使用不安全的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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