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

查看:950
本文介绍了暂时将[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)
}

在big-endian计算机上,此功能无法完成您想要的;您需要一个小尾数字节顺序.您只能将此作为针对低端字节序计算机的优化,并且需要坚持使用像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天全站免登陆