我有 u16 值,想将其转换为两个 u8 值以将其放入 u8 数组中,与此处所述相同。
0000000000000011 -> 00000000 and 00000011
Run Code Online (Sandbox Code Playgroud)
我该如何以方便的方式做到这一点?
将@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)
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |