I have a [u8; 16384]
and a u16
. How would I "temporarily transmute" the array so I can set the two u8
s at once, the first to the least significant byte and the second to the most significant byte?
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]
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.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)
}
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.