Rust字节数组和整型互转

整型转字节数组

小端序:i16::to_le_bytes

大端序:i16::to_be_bytes

字节数组转整型

小端序:i16::from_le_bytes

大端序:i16::from_be_bytes

例子

fn main() {
    let bytes: [u8; 2] = [1, 2];
    assert_eq!(i16::from_le_bytes(bytes), (2 << 8) + 1);
    assert_eq!(i16::from_be_bytes(bytes), (1 << 8) + 2);
    let x: i16 = (2 << 8) + 1;
    assert_eq!([1, 2], x.to_le_bytes());
    assert_eq!([2, 1], x.to_be_bytes());
}

参考文献

https://crates.io/crates/byteorder

posted @ 2024-09-28 14:16  寻找繁星  阅读(32)  评论(0编辑  收藏  举报