How would I cast a byte array to a primitive type in Rust?
let barry = [0, 0];
let shorty: u16 = barry;
I have already tried let shorty: u16 = barry as u16;
but that didn't work due to a "non scalar cast".
You can use bitwise operations. Note that this depends on endianess.
fn main() {
let barry = [0, 0];
let shorty: u16 = barry[0] | (barry[1] << 8);
println!("{0}", shorty);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With