如何在Rust中将u16的低/高8位转换为u8?

8
我想将一个 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

这个问题不是“为什么编译器会出现类型不匹配的错误?”,而是“如何在Rust中将u16的低/高8位转换为u8?”可能有其他方法可以做到这一点,而且这个问题并不限制答案只能使用as关键字。

2个回答

22
更新:截至Rust 1.32.0,现在有一个u16::to_be_bytes函数,可以用来代替自定义函数。
fn main() {
    let bytes = 28923u16.to_be_bytes();
    assert_eq!([0x70, 0xFB], bytes);
}
您可以使用as关键字以安全的方式将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
}

8

您可以使用as在不同的整数类型之间进行转换。

let b1 = n2 as u8;
let b2 = (n2 >> 8) as u8;

请注意,掩码是不必要的,因为强制转换将截断上位比特。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接