use*_*570 -3 arrays x86-64 rust
由于数组的长度,我不能使用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);
}
Run Code Online (Sandbox Code Playgroud)
但是有没有更干净的方法来做到这一点,同时仍然不复制数组?
提取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()));
}
Run Code Online (Sandbox Code Playgroud)
输出:
302055424
Run Code Online (Sandbox Code Playgroud)