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.

RustData Integrity

Code

rustsnippet
23 lines
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

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:`.