swap_bytes Endianness Conversion
Reverse integer byte order with swap_bytes and pair it with to_be_bytes and from_be_bytes so wire formats survive a host switch.
Code
fn main() {
let local: u32 = 0x0102_0304;
// swap_bytes:逐字节镜像,与宿主平台无关的纯位操作
println!("swapped: {:#010x}", local.swap_bytes());
// to_be_bytes / to_le_bytes 按目标序产出定长数组
let be = local.to_be_bytes();
let le = local.to_le_bytes();
println!("be: {:02x?} le: {:02x?}", be, le);
// from_be_bytes 是 to_be_bytes 的逆操作(宿主是小端时内部即做 swap_bytes)
println!("roundtrip: {}", u32::from_be_bytes(be) == local);
// 网络字节序惯例是大端:先 to_be 存,读时 from_be 还原
let port: u16 = 8080;
let wire = port.to_be();
println!("wire: {wire:#06x} host: {}", u16::from_be(wire));
// 64 位类型同样逐字节镜像
let wide: u64 = 0x0000_00FF_0000_00AA;
println!("wide swapped: {:#018x}", wide.swap_bytes());
}Byte order under the hood
Under the hood: the function main.
Points of care
- No crates are involved; every method is defined on the integer primitives.
Using it
The whole run happens inside fn main()
The file’s steps show up in the output as swapped:, be:, roundtrip:.
Conversion calls worth reading
let wide: u64 = 0x0000_00FF_0000_00AA;
let local: u32 = 0x0102_0304;
let be = local.to_be_bytes();
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- What does swap_bytes Endianness Conversion print when run?
- Run it as a complete program — the output lines carry labels such as `swapped:`, `be:`, `roundtrip:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.