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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.