u128 Wide Multiplication Splits Products

Widen u64 factors into u128 so a full 128-bit product stays exact, then split it into high and low halves with shifts and casts.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    let a: u64 = 0xFFFF_FFFF_FFFF_FFFF;
    let b: u64 = 0xFFFF_FFFF_FFFF_FFFF;

    // u64 * u64 在 u64 里必然溢出;先升到 u128 再乘,乘积完整保留
    let product = (a as u128) * (b as u128);
    println!("product fits u128: {}", product > u64::MAX as u128);

    // 拆高低半积:高 64 位与低 64 位各自还原成 u64
    let high = (product >> 64) as u64;
    let low = product as u64;
    println!("high: {high:#x}  low: {low:#x}");

    // 用移位重组验证拆分无损:回到 u128 后与原乘积一致
    let recombined = ((high as u128) << 64) | (low as u128);
    println!("lossless: {}", recombined == product);

    // 同一技巧可用于定点乘法:保留高半部作为缩放后的结果
    let scaled = high;
    println!("top half as scaled result: {scaled:#x}");
}

What the code does

u128 Wide Multiplication Splits Products keeps everything in the function main.

Watch out for

  • Built-in APIs only, so there is no supply chain to vet.

Applying it

Output lines are prefixed (product fits u128:, high:, lossless:), making each step’s effect easy to spot.

Statements that carry the weight

let recombined = ((high as u128) << 64) | (low as u128);
let product = (a as u128) * (b as u128);
let a: u64 = 0xFFFF_FFFF_FFFF_FFFF;

Interactive Tools for This Topic

FAQ

What does u128 Wide Multiplication Splits Products print when run?
No setup needed: run the file and look for labeled lines like `product fits u128:`, `high:`, `lossless:` in the output.