How can I convert Vec<u32>
to bytes, such that [1, 2, 4]
should give me [1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0]
, and to take the inverse bytes and convert them back to a vector of integers?
I only know how to convert [u8; 4]
into an integer.
Maybe you are looking for ByteOrder
:
use byteorder::{ByteOrder, LittleEndian};
fn main() -> () {
let rdr = vec![1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0];
let mut dst = [0; 3];
LittleEndian::read_u32_into(&rdr, &mut dst);
assert_eq!([1,2,4], dst);
let mut bytes = [0; 12];
LittleEndian::write_u32_into(&dst, &mut bytes);
assert_eq!(rdr, bytes);
}
And add the crate to Cargo.toml
[dependencies]
byteorder = "1.4.3"
You may use this (from Vec<u32>
to Vec<u8>
or vice versa):
extern crate byteorder;
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
fn main() {
let v32: Vec<u32> = vec![1, 2, 4];
let mut v8: Vec<u8> = Vec::new();
for n in v32 {
v8.write_u32::<LittleEndian>(n).unwrap();
}
println!("{:?}", v8); // [1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0]
let mut result: Vec<u32> = Vec::new();
for i in (0..v8.len()).step_by(4) {
result.push(LittleEndian::read_u32(&v8[i..]));
}
println!("{:?}", result); // [1, 2, 4]
}
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