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


GO Add64用法及代码示例


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

用法:

func Add64(x, y, carry uint64)(sum, carryOut uint64)

Add64 返回 x、y 和进位的总和:sum = x + y + 进位。进位输入必须为 0 或 1;否则行为未定义。进位输出保证为 0 或 1。

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

例子:

package main

import (
	"fmt"
	"math/bits"
)

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

输出:

[33 12] + [21 23] = [54 35] (carry bit was 0)
[1 9223372036854775808] + [1 9223372036854775808] = [3 0] (carry bit was 1)

相关用法


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