Related Articles
bits.OnesCount() Function in Golang with Examples
• Last Updated : 19 Apr, 2020

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 OnesCount() function which is used to find the number of one bits in a. To access the OnesCount() function you need to add a math/bits package in your program with the help of the import keyword.

Syntax:

`func OnesCount(a uint) int`

Parameters: This function takes one parameter of uint type, i.e., a.
Return Value: This function returns the total number of one bits that are used to represent a.

Example 1:

 `// Golang program to illustrate bits.OnesCount() Function ` `package main ` ` `  `import ( ` `    ``"fmt"` `    ``"math/bits"` `) ` ` `  `// Main function ` `func main() { ` ` `  `    ``// Using OnesCount() function ` `    ``a := bits.OnesCount(3) ` `    ``fmt.Printf(``"Total number of one bits "``+ ` `     ``"that are used to represent %d: %d"``, 3, a) ` ` `  `} `

Output:

`Total number of one bits that are used to represent 3: 2`

Example 2:

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

Output:

```OnesCount(101) = 2
OnesCount(1100) = 2
```

My Personal Notes arrow_drop_up
Recommended Articles
Page :