Go 语言提供了对位的内置支持,以在位包的帮助下为预先声明的无符号整数类型实现位计数和操作功能。该包提供了Add64()函数,用于求 a、b 和进位进位的和,即 sum = a + b +carry。这里carry的值必须是0或1,否则行为未定义。要访问 Add64()函数,您需要借助 import 关键字在程序中添加一个 math/bits 包。
Syntax:
Parameters: This function takes three parameters of uint64 type, i.e., a, b, and carry. The value of carry parameter is either 1 or 0.
Return Value: This function return two values of uint64 type, i.e., sum and carryout. Here sum contains the result of a + b + carry and carryout is either 1 or 0.
示例 1:
func Add64(a, b, carry uint64) (sum, carryout uint64)
输出:
// Golang program to illustrate bits.Add64() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Finding sum and carry
// of the specified numbers
// Using Add64() function
nvalue_1, carry := bits.Add64(23, 34, 1)
fmt.Println("Sum:", nvalue_1)
fmt.Println("Carry:", carry)
}
示例 2:
Sum: 58
Carry: 0
输出:
// Golang program to illustrate bits.Add64() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Finding sum and carry
// of the specified numbers
// Using Add64() function
var a, b, carry uint64 = 34, 56, 0
sum, carryout := bits.Add64(a, b, carry)
fmt.Println("Number 1:", a)
fmt.Println("Number 2:", b)
fmt.Println("Carry:", carry)
fmt.Println("Sum:", sum)
fmt.Println("Carry:", carryout)
}