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?
相关问题
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
- Newtonsoft DeserializeXNode expands internal array
相关文章
- How can I convert a f64 to f32 and get the closest
- Numpy matrix of coordinates
-
What is the difference between
and in java - What is a good way of cleaning up after a unit tes
- PHP: Can an array have an array as a key in a key-
- Why do I have to cast enums to int in C#?
- Accessing an array element when returning from a f
- How can I convert a PHP function's parameter l
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 au16
. 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: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.
The obvious, safe and portable way is to just use math.
If you want a higher-level interface, there's the
byteorder
crate which is designed to do this.You should definitely not use
transmute
to turn a[u8]
into a[u16]
, because that doesn't guarantee anything about the byte order.