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