Antonin GAVREL
Antonin GAVREL

Reputation: 11259

Convert array (or vector) of u16 (or u32, u64) to array of u8

I have no problem to do it for u16 to u8 using bit shifts and cast but how could I do it with an array of u16? Even ideally I would prefer to convert directly from vec to [u8]. What would be the most elegant way to do it?

&my_vector[..] // my vector converted to [u16] but I need [u8]

Upvotes: 2

Views: 4299

Answers (1)

Antonin GAVREL
Antonin GAVREL

Reputation: 11259

Was able to make it work thanks to @Aplet123 insight:

From Vector to bytes array

From Vec to [u8]

let mut my_u16_vec : Vec<u16> = Vec::new();
let my_u8_array = my_u16_vec.align_to::<u8>().1;

From bytes array back to Vector

From [u8] to Vec

let n = my_u16_vec.len() * 2;
let my_u16_vec_bis:Vec<u16> = (my_u8_array[..n].align_to::<u16>().1).to_vec();

Getting the bytes right

And then reverse bytes as values are written reversely in memory due to endianness:

for e in my_u16_vec_bis:Vec.iter() {
    let value = e >> 8 | (e & 0xff) << 8;
}

Upvotes: 4

Related Questions