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?")
}
I would do a typecast in C, but what do I do in Rust?
I'd suggest using the byteorder crate:
This handles oddly-sized slices and automatically advances the buffer so you can read multiple values.
As of Rust 1.32, you can also use the
from_le_bytes
/from_be_bytes
/from_ne_bytes
inherent methods on integers:This only handles arrays of a known size to avoid dealing with the error when not enough data is present.
See also: