当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Sub64用法及代码示例


GO语言"math/bits"包中"Sub64"函数的用法及代码示例。

用法:

func Sub64(x, y, borrow uint64)(diff, borrowOut uint64)

Sub64 返回 x、y 和借位的差:diff = x - y - 借位。借位输入必须为 0 或 1;否则行为未定义。 borrowOut 输出保证为 0 或 1。

此函数的执行时间不依赖于输入。

例子:

package main

import (
	"fmt"
	"math/bits"
)

func main() {
	// First number is 33<<64 + 23
	n1 := []uint64{33, 23}
	// Second number is 21<<64 + 12
	n2 := []uint64{21, 12}
	// Sub them together without producing carry.
	d1, carry := bits.Sub64(n1[1], n2[1], 0)
	d0, _ := bits.Sub64(n1[0], n2[0], carry)
	nsum := []uint64{d0, d1}
	fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)

	// First number is 3<<64 + 9223372036854775807
	n1 = []uint64{3, 0x7fffffffffffffff}
	// Second number is 1<<64 + 9223372036854775808
	n2 = []uint64{1, 0x8000000000000000}
	// Sub them together producing carry.
	d1, carry = bits.Sub64(n1[1], n2[1], 0)
	d0, _ = bits.Sub64(n1[0], n2[0], carry)
	nsum = []uint64{d0, d1}
	fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
}

输出:

[33 23] - [21 12] = [12 11] (carry bit was 0)
[3 9223372036854775807] - [1 9223372036854775808] = [1 18446744073709551615] (carry bit was 1)

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Sub64。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。