使用库函数获取给定数字所需总位数的Go语言程序


在这篇文章中,我们将讨论如何使用Go语言的库函数来获取给定数字所需的总位数。

要获得任何数字的总位数,我们需要将其转换为二进制表示(由零和一组成),然后计算零和一的个数。

例如:16可以转换为二进制10000,因此数字16的位数是5。

65可以转换为二进制1000001,因此数字65的位数是7。

语法

函数 -

func function_name([parameters]) [return_types]
{
   // Body of the function
}

for循环作为while循环 -

for condition {
   // code to be executed
   // increment or decrement the count variable.
}

使用库函数查找给定数字所需的总位数

算法

  • 步骤1 - 导入fmt和bits包。

  • 步骤2 - 初始化并定义将实现逻辑的getBits()函数。

  • 步骤3 - 开始main()函数

  • 步骤4 - 初始化无符号整型变量并赋值。

  • 步骤5 - 调用getBits()函数。

  • 步骤6 - 将结果存储在变量中

  • 步骤7 - 在屏幕上打印结果。

示例

使用库函数获取给定数字所需总位数的Go语言程序。

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()函数。

  • 初始化并定义无符号整型变量并赋值。这是我们想要计算其位数的数字。

  • 调用getBits()函数并将此数字作为参数传递。

  • getBits()函数接收一个无符号整数值并以整型格式返回结果。

  • 然后我们可以打印所选值的二进制格式,并使用内置的bits.Len()函数获取构成该数字的总位数的长度。

  • 将结果存储在一个单独的变量中并返回此值。

  • 将函数返回的值存储在main()中。

  • 使用fmt.Printf()函数在屏幕上打印结果。

结论

我们已经成功编译并执行了Go语言程序,以获取给定程序所需的总位数,并使用库函数提供了示例。

更新于:2022年10月25日

432次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.