实现说明
活动部件是函数 main。
使用要点
- 碰到的每个符号都是语言内建——没有要拉取的东西。
- 跑完文件,输出里会留下标记——
quotient=、reconstruct matches:、5-3 =。
常见问题
运行「bits.Div64 与 Sub64 带借位运算」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 quotient=、reconstruct matches:、5-3 = 标签标明各步骤。
核心语句
sumLo, carry := bits.Add64(prodLo, r, 0)
代码示例
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)
}