Skip to content

Latest commit

 

History

History
41 lines (33 loc) · 1.08 KB

endian-byte.zh.md

File metadata and controls

41 lines (33 loc) · 1.08 KB

以小端序,读取和写入整数

[![byteorder-badge]][byteorder] [![cat-encoding-badge]][cat-encoding]

byteorder可以反转,结构化数据的有效字节。这对网络上的信息接收,还有类似另一个系统的字节来说,可能会有必要。

extern crate byteorder;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::Error;

#[derive(Default, PartialEq, Debug)]
struct Payload {
    kind: u8,
    value: u16,
}

fn main() -> Result<(), Error> {
    let original_payload = Payload::default();
    let encoded_bytes = encode(&original_payload)?;
    let decoded_payload = decode(&encoded_bytes)?;
    assert_eq!(original_payload, decoded_payload);
    Ok(())
}

fn encode(payload: &Payload) -> Result<Vec<u8>, Error> {
    let mut bytes = vec![];
    bytes.write_u8(payload.kind)?;
    bytes.write_u16::<LittleEndian>(payload.value)?;
    Ok(bytes)
}

fn decode(mut bytes: &[u8]) -> Result<Payload, Error> {
    let payload = Payload {
        kind: bytes.read_u8()?,
        value: bytes.read_u16::<LittleEndian>()?,
    };
    Ok(payload)
}