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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…