Gar*_*ner 6

将@apilat和@Anton提供的答案放入代码中:

位移位 - 详细风格

这可以通过几种不同的方式来完成。实际上,我认为位移位更清晰一些,因为不需要考虑是否需要担心字节顺序。

逐一拼出:

fn shift_verbose_split_u16(short_16: u16) -> [u8; 2] {

    let high_byte: u8 = (short_16 >> 8) as u8;
    let low_byte: u8 = (short_16 & 0xff) as u8;

    return [high_byte, low_byte];
}
Run Code Online (Sandbox Code Playgroud)

位移位 - 惯用风格

上面的代码可以简化为一行函数:

fn shift_idiomatic_split_u16(short_16: u16) -> [u8; 2] {
    [(short_16 >> 8) as u8, (short_16 & 0xff) as u8]
}
Run Code Online (Sandbox Code Playgroud)

使用to_be_bytes()

使用to_be_bytes()当然是最简单的解决方案。使用此解决方案,您必须意识到您确实想要使用大端调用,而不管底层 cpu 的架构如何:

let [high, low] = short_16.to_be_bytes();
Run Code Online (Sandbox Code Playgroud)

将代码分组到一个文件中:

fn main() {
    let short_16: u16 = 0x3f23;
    
    // verbose bit shifting
    let [high, low] = shift_verbose_split_u16(short_16);
    assert_eq!(high, 0x3f);
    assert_eq!(low, 0x23);

    // idiomatic bit shifting
    let [high, low] = shift_idiomatic_split_u16(short_16);
    assert_eq!(high, 0x3f);
    assert_eq!(low, 0x23);

    let [high, low] = short_16.to_be_bytes();
    assert_eq!(high, 0x3f);
    assert_eq!(low, 0x23);

    println!("High: {:#0x?}, Low: {:#0x?}", high, low);   
}

fn shift_verbose_split_u16(short_16: u16) -> [u8; 2] {

    let high_byte: u8 = (short_16 >> 8) as u8;
    let low_byte: u8 = (short_16 & 0xff) as u8;

    return [high_byte, low_byte];
}

fn shift_idiomatic_split_u16(short_16: u16) -> [u8; 2] {
    [(short_16 >> 8) as u8, (short_16 & 0xff) as u8]
}
Run Code Online (Sandbox Code Playgroud)

输出:

High: 0x3f, Low: 0x23
Run Code Online (Sandbox Code Playgroud)