我想将u16
转换为两个单独的u8
。我尝试使用一些掩码:
use std::convert::From;
fn main() {
let n1: u8 = 0x41;
let n2: u16 = 0x4157;
println!("Number:{}", char::from(n1));
let b1: u8 = n2 & 0xFF;
let b2: u8 = n2 >> 8;
println!("b1: {}", b1);
println!("b2: {}", b2);
}
error[E0308]: mismatched types
--> src/main.rs:9:18
|
9 | let b1: u8 = n2 & 0xFF;
| ^^^^^^^^^ expected u8, found u16
error[E0308]: mismatched types
--> src/main.rs:10:18
|
10 | let b2: u8 = n2 >> 8;
| ^^^^^^^ expected u8, found u16
这个问题不是为什么编译器会引发类型不匹配的错误?,而是如何将u16
的低8位转换为Rust中的u8
?。可能还有其他方法可以执行此操作,并且此问题并不限制对as
关键字的回答。
答案 0 :(得分:6)
更新:从Rust 1.32.0开始,有u16::to_be_bytes
,可用于支持自定义功能。
fn main() {
let bytes = 28923u16.to_be_bytes();
assert_eq!([0x70, 0xFB], bytes);
}
您可以使用as
keyword以安全的方式将u16
转换为u8
。
fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] {
[(integer >> 8) as u8, integer as u8]
}
如果您需要更多类型或不同的字节序,请使用byteorder crate。
extern crate byteorder;
use byteorder::{WriteBytesExt, BigEndian};
fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8> {
let mut res = vec![];
res.write_u16::<BigEndian>(integer).unwrap();
res
}
答案 1 :(得分:4)
您可以使用as
在整数类型之间进行转换。
let b1 = n2 as u8;
let b2 = (n2 >> 8) as u8;
请注意,屏蔽是不必要的,因为强制转换会截断高位。