pub fn swap_bytes(builder: &CircuitBuilder, input: Wire) -> WireExpand description
Reverses the byte order of a 64-bit word.
This function swaps the bytes of the input word, converting between
little-endian and big-endian representations. It implements the same
operation as the Rust standard library’s u64::swap_bytes().
§Algorithm
The implementation is decomposed into two steps:
- Swap bytes within each 32-bit half independently using
swap_bytes_32 - Rotate the entire word by 32 bits to swap the halves
This is equivalent to the full Hacker’s Delight byte reversal algorithm but expressed more modularly.
§Arguments
builder- The circuit builder to add constraints toinput- Wire containing the 64-bit value to swap bytes of
§Returns
- Wire containing the byte-swapped result
§Cost Analysis
- Uses
swap_bytes_32: 4 shifts, 4 ANDs, 2 XORs - Plus 1 rotation (implemented as 2 shifts + 1 XOR internally)
- Total: 6 shift operations, 4 AND operations, 3 XOR operations
All shifts are free in Binius64 when part of constraints, making this approach very efficient.
§Example
ⓘ
use binius_core::word::Word;
use binius_frontend::crate::bytes::swap_bytes;
use binius_frontend::compiler::CircuitBuilder;
// Build circuit
let mut builder = CircuitBuilder::new();
let input = builder.add_witness();
let output = builder.add_witness();
let swapped = swap_bytes(&builder, input);
builder.assert_eq("swap_bytes_result", swapped, output);
let circuit = builder.build();
// Fill witness
let mut w = circuit.new_witness_filler();
w[input] = Word(0x0123456789ABCDEF);
w[output] = Word(0xEFCDAB8967452301); // Bytes reversed
// Verify
circuit.populate_wire_witness(&mut w).unwrap();§Reference
Based on the byte swapping algorithm from “Hacker’s Delight” by Henry S. Warren Jr.