std-method

Integer swap_bytes and endian conversion

Reverse byte positions unconditionally with swap_bytes, or transform an integer according to the native order using endian conversion methods. Prefer byte-array methods for serialization. Expected stdout (not executed): 04030201 true Common mistake: to_be returns an integer, not an array of bytes.

Formal Syntax & Structure

rust syntaxrust
x.swap_bytes(); x.to_be(); x.to_le(); u32::from_be(x); u32::from_le(x)

Working Example

Example Snippetrust
fn main() {    let x = 0x0102_0304_u32;    println!("{:08x}", x.swap_bytes());    println!("{}", u32::from_be(x.to_be()) == x);}
Rust Reference