Wide Addition And Multiplication With bits
Extend 64-bit arithmetic with math/bits.Add64 and bits.Mul64, which surface carries and high halves so multi-word sums and products stay exact.
Code
package main
import (
"fmt"
"math/bits"
)
func main() {
// Add64 返回 (sum, carryOut):两个 64 位加数的和与进位
sum, carry := bits.Add64(0xFFFF_FFFF_FFFF_FFFF, 1, 0)
fmt.Printf("sum=%d carry=%d\n", sum, carry)
// 带进位的三数相加:低位和 + 上一步进位
lo, mid := bits.Add64(0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF_FFFF_FFFF, 0)
_, carry2 := bits.Add64(lo, 1, mid)
fmt.Println("two max + 1 overflow carry:", carry2)
// Mul64 返回 (hi, lo):128 位乘积拆成高低两半,永不丢位
hi, lo := bits.Mul64(0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF_FFFF_FFFF)
fmt.Printf("product hi=%#x lo=%#x\n", hi, lo)
// 128 位乘积可以无损还原:(hi,lo) 组合值超出 uint64 范围
fmt.Println("hi nonzero:", hi != 0, "lo:", lo)
}How it works
Everything happens inside the function main.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The primary signature, spelled out, is func main()
Watch for labeled lines in the run — sum=, two max + 1 overflow carry:, product hi= — when the file runs.
Key statements worth quoting
lo, mid := bits.Add64(0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF_FFFF_FFFF, 0)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.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.
FAQ
- What does Wide Addition And Multiplication With bits print when run?
- No setup needed: run the file and look for labeled lines like `sum=`, `two max + 1 overflow carry:`, `product hi=` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.