bits.Div64 And Sub64 Borrowed Math
Perform 128-by-64 division with bits.Div64 and subtract-with-borrow using bits.Sub64, completing the wide-arithmetic pair next to Add64 and Mul64.
Code
package main
import (
"fmt"
"math/bits"
)
func main() {
// Div64(hi, lo, y):128 位被除数 (hi,lo) 除以 y,返回商与余数
// 前置条件 hi < y,否则结果无法放进 64 位(会 panic)
const lo = 0xFFFF_FFFF_FFFF_FFFF
const hi = uint64(2)
q, r := bits.Div64(hi, lo, 7)
fmt.Printf("quotient=%d remainder=%d\n", q, r)
// 用乘法反向验证:q*7 + r == 原被除数
prodHi, prodLo := bits.Mul64(q, 7)
sumLo, carry := bits.Add64(prodLo, r, 0)
sumHi, _ := bits.Add64(prodHi, 0, carry)
fmt.Println("reconstruct matches:", sumHi == hi && sumLo == lo)
// Sub64(x, y, borrow):x-y-borrow,返回差与借位
diff, borrowOut := bits.Sub64(5, 3, 0)
fmt.Println("5-3 =", diff, "borrow:", borrowOut)
// 0-1 需要借位:差回绕到 max,借位为 1
diff2, borrowOut2 := bits.Sub64(0, 1, 0)
fmt.Println("0-1 =", diff2, "borrow:", borrowOut2)
}The steps the file takes
bits.Div64 And Sub64 Borrowed Math comes down to the function main.
What to watch for
- fmt and math/bits are the whole import list, both part of the standard distribution.
Using it
Signature: func main()
The demo output is labeled (quotient=, reconstruct matches:, 5-3 =); each label names the call that printed it.
Key statements
sumLo, carry := bits.Add64(prodLo, r, 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 bits.Div64 And Sub64 Borrowed Math print when run?
- The script runs standalone; its 4 labeled outputs include `quotient=`, `reconstruct matches:`, `5-3 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.