Golang程序 使用库函数获取给定数字所需的总比特数
在这篇文章中,我们将讨论如何使用Go语言中的库函数获得给定数字所需的总位数。
为了得到任何数字的总位数,我们需要用二进制表示该数字,即零和一的组合,然后计算零和一的数量。
例如:16可以用二进制转换为10000,因此16的比特数为5。
65可以用二进制转换为1000001,因此65的比特数为7。
语法
Functions −
func function_name([parameters]) [return_types]
{
// Body of the function
}
作为一个while循环的For循环 –
for condition {
// code to be executed
// increment or decrement the count variable.
}
使用函数库查找给定数字所需的总位数
算法
- 第1步 – 导入软件包fmt和bits。
-
第2步 – 初始化并定义getBits()函数,该函数将实现该逻辑。
-
第3步 – 启动main()函数
-
第4步 – 初始化无符号int数据类型的变量并为其赋值。
-
第5步– 调用getBits()函数。
-
第6步 – 将结果存储在一个变量中
-
第7步 – 在屏幕上打印结果。
例子
Golang程序使用库函数获得给定数字所需的总位数。
package main
import (
"fmt"
"math/bits"
)
// fmt package allows us to print anything on the screen.
// 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()函数。
-
初始化和定义无符号int变量,并为其赋值。这就是我们希望计算的比特数。
-
调用getBits()函数并将这个数字作为参数传入其中。
-
getBits()函数接收一个无符号整数值并以整数格式返回结果。
-
然后,我们可以打印所选数值的二进制格式,并使用内置的bits.Len()函数来获得构成该数字的总比特的长度。
-
将结果存储在一个单独的变量中并返回这个值。
-
将函数返回的值存储在main()中。
-
使用fmt.Printf()函数在屏幕上打印结果。
总结
我们已经成功地编译并执行了Go语言程序,以获得一个给定程序所需的总位数,同时还有使用库函数的例子。
极客教程