And convert a number to a byte array?
I'd like to avoid using transmute
, but it's most important to reach maximum performance.
A u32
being 4 bytes, you may be able to use std::mem::transmute
to interpret a [u8; 4]
as a u32
however:
A no-dependency solution is simply to perform the maths, following in Rob Pike's steps:
fn as_u32_be(array: &[u8; 4]) -> u32 {
((array[0] as u32) << 24) +
((array[1] as u32) << 16) +
((array[2] as u32) << 8) +
((array[3] as u32) << 0)
}
fn as_u32_le(array: &[u8; 4]) -> u32 {
((array[0] as u32) << 0) +
((array[1] as u32) << 8) +
((array[2] as u32) << 16) +
((array[3] as u32) << 24)
}
It compiles down to reasonably efficient code.
If dependencies are an option though, using the byteorder crate is just simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With