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.

GoData Integrity

Code

gosnippet
24 lines
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

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.