the*_*ian 2 bit-manipulation rust
我想将a转换u16为两个单独的u8s。我尝试使用一些掩码:
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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
这个问题不是为什么编译器会引发不匹配的类型错误?,相反,它是如何在Rust中将a的低8位转换u16为a u8?。潜在地,还有其他方法可以执行此操作,并且此问题不限制as关键字的答案。
更新:从Rust 1.32.0开始u16::to_be_bytes,提供了,可用于支持自定义功能。
fn main() {
let bytes = 28923u16.to_be_bytes();
assert_eq!([0x70, 0xFB], bytes);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用as关键字的转换u16,以u8一种安全的方式。
fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] {
[(integer >> 8) as u8, integer as u8]
}
Run Code Online (Sandbox Code Playgroud)
如果需要更多类型或不同的字节序,请使用字节顺序板条箱。
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
}
Run Code Online (Sandbox Code Playgroud)
您可以使用进行整数类型之间的转换as。
let b1 = n2 as u8;
let b2 = (n2 >> 8) as u8;
Run Code Online (Sandbox Code Playgroud)
注意,屏蔽是不必要的,因为强制类型转换将截断高位。