暂时将 [u8] 转化为 [u16] [英] Temporarily transmute [u8] to [u16]

查看:77
本文介绍了暂时将 [u8] 转化为 [u16]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 [u8;16384]u16.我将如何临时转换"数组,以便我可以一次设置两个 u8,第一个到最低有效字节,第二个到最高有效字节?

I have a [u8; 16384] and a u16. How would I "temporarily transmute" the array so I can set the two u8s at once, the first to the least significant byte and the second to the most significant byte?

推荐答案

正如 DK 建议的,你可能不应该真正使用 unsafe 代码来重新解释内存......但如果你愿意,你可以.

As DK suggests, you probably shouldn't really use unsafe code to reinterpret the memory... but you can if you want to.

如果你真的想走那条路,你应该注意几个问题:

If you really want to go that route, you should be aware of a couple of gotchas:

  • 您可能遇到对齐问题.如果您只是从某处获取一个 &mut [u8] 并将其转换为 &mut [u16],它可能指的是某些不正确的内存区域对齐以作为 u16 访问.根据您运行此代码的计算机,这种未对齐的内存访问可能是非法的.在这种情况下,程序可能会以某种方式中止.例如,CPU 可以生成操作系统响应的某种信号以终止进程.
  • 它将是不可携带的.即使没有对齐问题,您在不同的机器上也会得到不同的结果(小端机器和大端机器).
  • You could have an alignment problem. If you just take a &mut [u8] from somewhere and convert it to a &mut [u16], it could refer to some memory region that is not properly aligned to be accessed as a u16. Depending on what computer you run this code on, such an unaligned memory access might be illegal. In this case, the program would probably abort somehow. For example, the CPU could generate some kind of signal which the operating system responds to in order to kill the process.
  • It'll be non-portable. Even without the alignment issue, you'll get different results on different machines (little- versus big-endian machines).

如果你可以切换它(创建一个u16数组并在字节级别临时处理它),你将解决潜在的内存对齐问题:

If you can switch it around (creating a u16 array and temporarily dealing with it on a byte level), you would solve the potential memory alignment problem:

/// warning: The resulting byte view is system-specific
unsafe fn raw_byte_access(s16: &mut [u16]) -> &mut [u8] {
    use std::slice;
    slice::from_raw_parts_mut(s16.as_mut_ptr() as *mut u8, s16.len() * 2)
}

在大端机器上,这个函数不会做你想做的;你想要一个小端字节序.您只能将其用作小端机器的优化,并且需要坚持使用 DK 之类的大端或混合端机器的解决方案.

On a big-endian machine, this function will not do what you want; you want a little-endian byte order. You can only use this as an optimization for little-endian machines and need to stick with a solution like DK's for big- or mixed-endian machines.

这篇关于暂时将 [u8] 转化为 [u16]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆