gpt4 book ai didi

arrays - 如何将 byte slice 段 (&[u8]) 的缓冲区转换为整数?

转载 作者:行者123 更新时间:2023-11-29 08:32:06 26 4
gpt4 key购买 nike

我正在从文件中读取原始数据,我想将其转换为整数:

fn main() {
let buf: &[u8] = &[0, 0, 0, 1];
let num = slice_to_i8(buf);
println!("1 == {}", num);
}

pub fn slice_to_i8(buf: &[u8]) -> i32 {
unimplemented!("what should I do here?")
}

我会在 C 中进行转换,但我在 Rust 中做什么?

最佳答案

我建议使用 byteorder crate (也适用于非标准环境):

use byteorder::{BigEndian, ReadBytesExt}; // 1.2.7

fn main() {
let mut buf: &[u8] = &[0, 0, 0, 1];
let num = buf.read_u32::<BigEndian>().unwrap();

assert_eq!(1, num);
}

这会处理奇怪大小的切片并自动推进缓冲区,以便您可以读取多个值。

从 Rust 1.32 开始,您还可以使用 from_le_bytes/from_be_bytes/from_ne_bytes整数的固有方法:

fn main() {
let buf = [0, 0, 0, 1];
let num = u32::from_be_bytes(buf);

assert_eq!(1, num);
}

这些方法只处理固定长度的数组,以避免在数据不足时处理错误。如果你有一片,你将需要 convert it into an array .

另见:

关于arrays - 如何将 byte slice 段 (&[u8]) 的缓冲区转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com