carrying_add Chains Carries Across Words
Build multi-word arithmetic on u64 with carrying_add and borrowing_sub, which expose the carry and borrow bits so 128-bit sums stay exact.
Code
fn main() {
// 128 位整数用两个 u64 表示:低位 + 高位
let (a_lo, a_hi) = (u64::MAX, 5);
let (b_lo, b_hi) = (1, 7);
// carrying_add(self, rhs, carry) 返回 (和, 进位):低位以 0 进位起算,
// 进位标志(0/1)喂给高位
let (sum_lo, carry) = a_lo.carrying_add(b_lo, 0);
let (sum_hi, _overflow) = a_hi.carrying_add(b_hi, carry as u64);
println!("128-bit sum: hi={sum_hi} lo={sum_lo} carry={carry}");
// borrowing_sub 返回 (差, 借位):低位不够减时高位要借
let (a_lo, a_hi) = (3, 10);
let (b_lo, b_hi) = (7, 2);
let (diff_lo, borrow) = a_lo.borrowing_sub(b_lo, 0);
let (diff_hi, _underflow) = a_hi.borrowing_sub(b_hi, borrow as u64);
println!("128-bit diff: hi={diff_hi} lo={diff_lo} borrow={borrow}");
// 对照普通 +:只在 u64 内回绕,进位信息直接丢失
println!("plain wrap: {}", u64::MAX.wrapping_add(1));
println!("overflow flag from checked: {}", u64::MAX.checked_add(1).is_none());
}How it works
Everything happens inside the function main.
Caveats
- No packages pulled in; the language’s built-in APIs carry all of the work here.
Putting it to use
Signature: fn main()
The output comes back labeled — 128-bit sum: hi=, 128-bit diff: hi=, plain wrap: — when the file runs.
The core lines of the flow
let (diff_hi, _underflow) = a_hi.borrowing_sub(b_hi, borrow as u64);
let (sum_hi, _overflow) = a_hi.carrying_add(b_hi, carry as u64);
let (diff_lo, borrow) = a_lo.borrowing_sub(b_lo, 0);
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.
FAQ
- What does carrying_add Chains Carries Across Words print when run?
- Run it as a complete program — the output lines carry labels such as `128-bit sum: hi=`, `128-bit diff: hi=`, `plain wrap:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.