from_be_bytes Roundtrips Wire Formats

Pack integers into fixed byte arrays with to_be_bytes and parse them back with from_be_bytes, keeping big-endian wire layouts exact.

RustData Integrity

Code

rustsnippet
28 lines
fn main() {
    let sequence: u32 = 0x1A2B_3C4D;

    // to_be_bytes:大端序写进定长数组;网络协议通常约定大端
    let wire: [u8; 4] = sequence.to_be_bytes();
    println!("wire bytes: {wire:02x?}");

    // from_be_bytes 是逆操作:字节数组还原为整数
    let parsed = u32::from_be_bytes(wire);
    println!("roundtrip exact: {}", parsed == sequence);

    // 小端序与原生序的差异:同一整数产出不同字节排列
    println!("le: {:02x?}", sequence.to_le_bytes());
    println!("ne: {:02x?}", sequence.to_ne_bytes());

    // 组合消息:u16 长度前缀 + u32 载荷,各自贡献定长字节
    let payload: u32 = 100;
    let len: u16 = 4;
    let mut frame = Vec::with_capacity(6);
    frame.extend_from_slice(&len.to_be_bytes());
    frame.extend_from_slice(&payload.to_be_bytes());
    println!("frame: {frame:02x?}");

    // 解码端按偏移切回字段
    let got_len = u16::from_be_bytes(frame[0..2].try_into().unwrap());
    let got_payload = u32::from_be_bytes(frame[2..6].try_into().unwrap());
    println!("decoded len={got_len} payload={got_payload}");
}

How the snippet works

The snippet is organized around the function main.

Points of care

  • Runs on the standard library alone; nothing to install.

Applying it

The primary signature is fn main()

The file announces its steps in the output: wire bytes:, roundtrip exact:, le:.

Statements that matter most here

let got_payload = u32::from_be_bytes(frame[2..6].try_into().unwrap());
let got_len = u16::from_be_bytes(frame[0..2].try_into().unwrap());

Interactive Tools for This Topic

FAQ

What does from_be_bytes Roundtrips Wire Formats print when run?
No setup needed: run the file and look for labeled lines like `wire bytes:`, `roundtrip exact:`, `le:` in the output.