Golang 程序使用库函数获取给定数字所需的总位数
在本文中,我们将讨论如何使用 Go 语言中的库函数获取给定数字所需的总位数。
要获取任何数字的总位数,我们需要以二进制表示该数字,即零和一的组合,然后计算零和一的数量。
例如:16 可以转换为二进制为 10000,因此数字 16 中的位数为 5。
65 可以转换为二进制为 1000001,因此数字 65 中的位数为 7。
语法
函数 −
func function_name([parameters]) [return_types] { // 正文函数 }
For 循环作为 while 循环 −
for condition { // 要执行的代码 // 增加或减少计数变量。 }
使用库函数查找给定数字所需的总位数
算法
步骤 1 - 导入包 fmt 和 bits。
步骤 2 - 初始化并定义将实现逻辑的 getBits() 函数。
步骤 3 - 启动 main() 函数
步骤 4 - 初始化无符号 int 数据类型的变量并为其赋值。
步骤 5 - 调用 getBits() 函数。
步骤 6 - 将结果存储在变量中
步骤 7 - 打印屏幕上的结果。
示例
Golang 程序使用库函数获取给定数字所需的总位数。
package main import ( "fmt" "math/bits" ) // fmt 包允许我们在屏幕上打印任何内容。 // bits package allows to perform bitwise operations to unsigned integer values like counting number of bits. func getBits(number uint) int { // getting the binary representation of the above chosen value fmt.Printf("Binary representation of %d is: %b\n", number, number) // initializing a variable to store the results var result int // getting the number of bits in the result variable result = bits.Len(number) // returning back the number of bits return result } func main() { // initializing a variable of unsigned integer data type var number uint // assigning value to the above initialized variable whose bits we wish to calculate number = 65 // calling the getBits() function and passing the number to it as the argument and getting back the result. result := getBits(number) // printing the number of bits of the chosen integer value fmt.Printf("Total number of bits in %d are : %d\n", number, result) }
输出
Binary representation of 65 is: 1000001 Total number of bits in 65 are : 7
代码说明
首先,我们导入 fmt 包,该包允许我们打印任何内容,以及 bits 包,该包允许我们使用按位运算。
然后,我们创建并定义了 getBits() 函数,该函数计算总位数并返回结果。
然后,我们启动 main() 函数。
初始化并定义 unsigned int 变量并为其赋值。这是我们希望计算其位的数字。
调用 getBits() 函数并将此数字作为参数传递。
getBits() 函数接收一个无符号整数值并以整数格式返回结果。
然后,我们可以打印所选值的二进制格式,并使用内置的 bits.Len() 函数获取形成数字的总位数。
将结果存储在单独的变量中并返回此值。
将函数返回的值存储在 main() 中。
使用 fmt.Printf() 函数将结果打印在屏幕上。
结论
我们已经成功编译并执行了 Go 语言程序,以获取给定程序所需的总位数以及使用库函数的示例。