如何将大于8字节的[u8]数组强制转换为整数



由于数组的长度,我不能使用i32::from_ne_bytes(),但当然,以下代码尤其有效,因为代码只能在支持未对齐访问的cpu架构上运行(或者由于长度较小,整个数组可能会存储在多个cpu寄存器中(。

fn main() {
let buf: [u8; 10] = [0, 0, 0, 1, 0x12, 14, 50, 120, 250, 6];
println!("1 == {}", unsafe{std::ptr::read(&buf[1])} as i32);
}

但是,有没有一种更干净的方法可以做到这一点,同时仍然不复制数组?

提取一个4字节的&[u8]切片,并使用try_into()将其转换为&[u8; 4]数组引用。然后您可以拨打i32::from_ne_bytes()

use std::convert::TryInto;
fn main() {
let buf: [u8; 10] = [0, 0, 0, 1, 0x12, 14, 50, 120, 250, 6];
println!("{}", i32::from_ne_bytes((&buf[1..5]).try_into().unwrap()));
}

输出:

302055424

游乐场

TL;DR:实际上,只要使用John Kugelman的解决方案,复制4个字节是不可测量的。

最大的";测量的">差值为0.09ps(239.79-239.70(,即90飞秒,即0.00009纳秒。再次运行基准测试,将产生截然不同的结果(在皮秒范围内(

像复制4个字节这样的东西是不现实的。我们远低于纳秒,这是纯粹的噪音。

测试 #[bench] criterion
try_into 0 ns 239.79 ps
重新解释 0 ns 239.70 ps
位解压缩 0 ns 239.74 ps
b.iter(|| 1) 240.18 ps
b.iter(|| 1) 239.73 ps
b.iter(|| 1) 239.68 ps

最新更新