在Rust中将整数向量与字节之间进行转换

时间:2019-02-01 04:38:33

标签: rust

在Rust中,我可以使用什么来将Vec<u32>转换为字节,以使[1,2,4]可以使我[1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0],并取反字节并将其转换回向量整数?

我只知道如何将[u8, 4]转换回整数

3 个答案:

答案 0 :(得分:2)

也许这就是您要寻找的https://docs.rs/byteorder/1.3.1/byteorder/trait.ByteOrder.html

extern crate byteorder; // 1.3.1
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);
}

答案 1 :(得分:1)

您可以使用this(从SliverAppBar( backgroundColor: Colors.blue, expandedHeight: 200.0, floating: true, // pinned: true, flexibleSpace: Center( child: ListView( shrinkWrap: true, children: <Widget>[ Row( children: <Widget>[ Spacer(), CircleAvatar( radius: 68.0, backgroundImage: NetworkImage( "https://placeimg.com/640/480/animals", ), ), Spacer(), ], ), Center( child: Text("Collapsing Toolbar", style: TextStyle( color: Colors.white, fontSize: 22.0, )), ), ], ), ), ), Vec<u32>,反之亦然):

Vec<u8>

答案 2 :(得分:-1)

您可以使用transmute解决此问题,但这将是不安全的:

let bytes: [u8; 4] = unsafe { transmute(u32_value.to_le()) };

您还可以创建自己的函数,将u32解析为字节片,如下所示:

fn transform_u32_to_array_of_u8(x: u32) -> [u8; 4] {
    let b1: u8 = ((x >> 24) & 0xff) as u8;
    let b2: u8 = ((x >> 16) & 0xff) as u8;
    let b3: u8 = ((x >> 8) & 0xff) as u8;
    let b4: u8 = (x & 0xff) as u8;
    return [b1, b2, b3, b4];
}

如果您不想创建自己的功能并希望依赖第三方板条箱,则可以看看bytes条板箱

Reference

这是您的问题的有效代码:

use std::mem::transmute;

fn main() {
    let my_vec_u32: Vec<u32> = vec![1, 2, 4];
    let mut my_vec_u8: Vec<u8> = Vec::new();

    my_vec_u32.iter().for_each(|u32_value| {
        // let bytes: [u8; 4] = transform_u32_to_array_of_u8(u32_value.clone());
        let bytes: [u8; 4] = unsafe { transmute(u32_value.to_le()) };
        bytes.iter().for_each(|byte| my_vec_u8.push(byte.clone()));
    });

    println!("{:?}", my_vec_u8);
}

fn transform_u32_to_array_of_u8(x: u32) -> [u8; 4] {
    let b1: u8 = ((x >> 24) & 0xff) as u8;
    let b2: u8 = ((x >> 16) & 0xff) as u8;
    let b3: u8 = ((x >> 8) & 0xff) as u8;
    let b4: u8 = (x & 0xff) as u8;
    return [b1, b2, b3, b4];
}

Playground