Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a byte array to a primitive type in Rust?

Tags:

casting

rust

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".

like image 379
Jeroen Avatar asked Aug 20 '14 21:08

Jeroen


1 Answers

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);
}
like image 164
Alexander Gessler Avatar answered Nov 04 '22 10:11

Alexander Gessler