如何在Rust中将u16的低8位转换为u8? [英] How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?

查看:339
本文介绍了如何在Rust中将u16的低8位转换为u8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 u16 转换为两个单独的 u8 .我尝试使用一些掩码:

I want to convert a u16 to two separate u8s. I tried to use some bit masks:

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位/高8位code>转换为Rust中的 u8 ?.潜在地,还有其他方法可以执行此操作,并且此问题不限制对 as 关键字的回答.

This question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

推荐答案

更新:从Rust 1.32.0开始,有

Update: As of Rust 1.32.0 there is u16::to_be_bytes, which can be used in favor a custom function.

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]
}

如果您需要更多类型或不同的字节序,请使用字节顺序箱.

If you need more types or different endianness use the 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
}

这篇关于如何在Rust中将u16的低8位转换为u8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆