Home Ask Login Register

Developers Planet

Your answer is one click away!

lu_zero February 2016

Which is the quickest, safe or unsafe, way to read 16, 32, 64 bit integers from a &u8[] in Rust?

Assume you have a slice and you want to read little and big endian integers from it. Is there a better way than to use unsafe pointers?


fjh February 2016

You could use the byteorder crate. For some usage examples, see the docs.

use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};

let mut rdr = Cursor::new(vec![2, 5, 3, 0]);
// Note that we use type parameters to indicate which kind of byte order
// we want!
assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap());
assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap());

Post Status

Asked in February 2016
Viewed 2,753 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life