Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have a way to convert several bytes to a number? [duplicate]

And convert a number to a byte array?

I'd like to avoid using transmute, but it's most important to reach maximum performance.

like image 764
Walking.In.The.Air Avatar asked Apr 16 '16 20:04

Walking.In.The.Air


1 Answers

A u32 being 4 bytes, you may be able to use std::mem::transmute to interpret a [u8; 4] as a u32 however:

  • beware of alignment
  • beware of endianness

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.

like image 104
Matthieu M. Avatar answered Nov 13 '22 20:11

Matthieu M.