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?
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?
The obvious, safe and portable way is to just use math.
fn set_u16_le(a: &mut [u8], v: u16) {
a[0] = v as u8;
a[1] = (v >> 8) as u8;
}
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.