I'd like to give this answer here to commit the following additional details:
- A working code snippet which converts slice to integer (two ways to do it).
- A working solution in
no_std
environment.
- To keep everything in one place for the people getting here from the search engine.
Without external crates, the following methods are suitable to convert from slices to integer even for no_std
build starting from Rust 1.32:
Method 1 (try_into
+ from_be_bytes
)
use core::convert::TryInto;
let src = [1, 2, 3, 4, 5, 6, 7];
// 0x03040506
u32::from_be_bytes(src[2..6].try_into().unwrap());
use core::conver::TryInto
is for no_std
build. And the way to use the standard crate is the following: use std::convert::TryInto;
.
(And about endians it has been already answered, but let me keep it here in one place: from_le_bytes, from_be_bytes, and from_ne_bytes - use them depending on how integer is represented in memory).
Method 2 (clone_from_slice
+ from_be_bytes
)
let src = [1, 2, 3, 4, 5, 6, 7];
let mut dst = [0u8; 4];
dst.clone_from_slice(&src[2..6]);
// 0x03040506
u32::from_be_bytes(dst);
Result
In both cases integer will be equal to 0x03040506
.