本文介绍了如何将字节片(& [u8])的缓冲区转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我建议使用字节顺序箱(也可在无std环境中使用):

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.

另请参阅:

  • How to get a slice as an array in Rust?
  • How to convert a slice into an array reference?

这篇关于如何将字节片(&amp; [u8])的缓冲区转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:59