bits.Len() Function in Golang with Examples

Go language provides inbuilt support for bits to implement bit counting and manipulation functions for the predeclared unsigned integer types with the help of bits package. This package provides Len() function which is used to find the minimum number of bits required to represent a and the result is 0 for a == 0. To access Len() function you need to add a math/bits package in your program with the help of the import keyword.

Syntax:

 func Len(a uint) int

Parameters: This function takes one parameter of uint type, i.e., a.

Return Value: This function returns the minimum number of bits required to represent a.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate bits.Len() Function
  
package main
  
import (
    "fmt"
    "math/bits"
)
  
// Main function
func main() {
  
    // Using Len() function
    a := bits.Len(3)
    fmt.Printf("The minimum number of bits "+
        "required to represent %d: %d", 3, a)
  
}

chevron_right


Output:

The minimum number of bits required to represent 3: 2

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate bits.Len() Function
  
package main
  
import (
    "fmt"
    "math/bits"
)
  
// Main function
func main() {
  
    // Using Len() function
    a1 := bits.Len(2)
    fmt.Printf("Len(%b) = %d\n", 2, a1)
  
    a2 := bits.Len(12)
    fmt.Printf("Len(%b) = %d\n", 12, a2)
  
}

chevron_right


Output:

Len(10) = 2
Len(1100) = 4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.