如何将float转换为二进制而不使用不安全的代码? [英] How to convert float to binary without using unsafe code?
问题描述
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屋!