Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector of integers to and from bytes? [duplicate]

Tags:

rust

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.

like image 666
nevi_me Avatar asked Mar 04 '23 14:03

nevi_me


2 Answers

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"
like image 114
Simson Avatar answered Mar 17 '23 22:03

Simson


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]
}
like image 31
wasmup Avatar answered Mar 17 '23 21:03

wasmup