【问题标题】:Convert array (or vector) of u16 (or u32, u64) to array of u8将 u16(或 u32、u64)的数组(或向量)转换为 u8 的数组
【发布时间】:2021-03-15 00:38:43
【问题描述】:

对于u16 to u8 使用位移和强制转换,我没有问题,但我怎么能用 u16 的数组来做呢?即使理想情况下,我更愿意直接从 vec 转换为 [u8]。最优雅的方法是什么?

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

【问题讨论】:

标签: rust


【解决方案1】:

感谢@Aplet123 的洞察力,能够使其工作:

从向量到字节数组

从 Vec 到 [u8]

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

从字节数组返回向量

从 [u8] 到 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();

正确获取字节

然后由于字节序将值反向写入内存中,然后反转字节:

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

【讨论】:

  • 请注意,您的“字节数组到向量”代码仅在字节数组正确对齐时才有效,如果它是通过网络套接字或文件发送的,则可能不会。
猜你喜欢
  • 2017-02-09
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多