如何将一段字节 (&[u8]) 的缓冲区转换为整数? [英] How can I convert a buffer of a slice of bytes (&[u8]) to an integer?
问题描述
我正在从文件中读取原始数据,我想将其转换为整数:
I am reading raw data from a file and I want to convert it to an integer:
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 中做什么?
I would do a cast in C, but what do I do in Rust?
推荐答案
我建议使用 byteorder crate(也适用于非标准环境):
I'd suggest using the byteorder crate (which also works in a no-std environment):
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);
}
这会处理奇怪大小的切片并自动推进缓冲区,以便您可以读取多个值.
This handles oddly-sized slices and automatically advances the buffer so you can read multiple values.
从 Rust 1.32 开始,您还可以使用 from_le_bytes
/from_be_bytes
/from_ne_bytes代码>
整数的固有方法:
As of Rust 1.32, you can also use the from_le_bytes
/ from_be_bytes
/ from_ne_bytes
inherent methods on integers:
fn main() {
let buf = [0, 0, 0, 1];
let num = u32::from_be_bytes(buf);
assert_eq!(1, num);
}
这些方法只处理固定长度的数组,以避免在数据不足时处理错误.如果您有切片,则需要将其转换为数组.
These methods only handle fixed-length arrays to avoid dealing with the error when not enough data is present. If you have a slice, you will need to convert it into an array.
另见:
这篇关于如何将一段字节 (&[u8]) 的缓冲区转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!