我想将一个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位转换为u8?潜在地,还有其他方法可以做到这一点,并且这个问题并不限制as关键字的答案。
发布于 2018-11-15 07:31:47
更新:在Rust 1.32.0中,有u16::to_be_bytes,它可以用于自定义函数。
fn main() {
let bytes = 28923u16.to_be_bytes();
assert_eq!([0x70, 0xFB], bytes);
}您可以使用关键字以安全的方式将u16转换为u8。
fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] {
[(integer >> 8) as u8, integer as u8]
}如果需要更多类型或不同的endianness,请使用附条箱。
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
}发布于 2018-11-15 07:31:53
您可以使用as在整数类型之间进行转换。
let b1 = n2 as u8;
let b2 = (n2 >> 8) as u8;请注意,掩蔽是不必要的,因为强制转换将截断上位。
https://stackoverflow.com/questions/53314005
复制相似问题