Menu Close

Go – How to get minimum number of bits required to represent a number in go

Here, We will learn about how to get minimum number of bits required to represent a number in go. Len() function of bits package is used most frequently.

There are multiple functions to get bits require to represent a number.

  • Len()
  • Len16()
  • Len32()
  • Len64()
  • Len8()

Function proto type:

func Len(x uint) int

func Len16(x uint16) int

func Len32(x uint32) int

func Len64(x uint64) int

func Len8(x uint8) int

Input parameters:

x: number

Code example:

package main

import (
  "fmt"
  "math/bits"
)


func main() {

    no := uint(16)

    x := bits.Len(no)

    fmt.Println("minimum number of bits required to represent number: ", x)


    no16 := uint16(32)

    x16 := bits.Len16(no16)

    fmt.Println("minimum number of bits required to represent number: ", x16)


    no32 := uint32(64)

    x32 := bits.Len32(no32)

    fmt.Println("minimum number of bits required to represent number: ", x32)


    no64 := uint64(128)

    x64 := bits.Len64(no64)

    fmt.Println("minimum number of bits required to represent number: ", x64)


    no8 := uint8(16)

    x8 := bits.Len8(no8)

    fmt.Println("minimum number of bits required to represent number: ", x8)

}

Output:

$ go run sample.go

 minimum number of bits required to represent number:  5  ==>> number = 16, in bits: 10000 i.e 5 bits

 minimum number of bits required to represent number:  6  ==>> number = 32, in bits: 100000 i.e 6 bits

 minimum number of bits required to represent number:  7  ==>> number = 64, in bits: 1000000 i.e 7 bits  

 minimum number of bits required to represent number:  8  ==>> number = 128, in bits: 10000000 i.e 8 bits
 
 minimum number of bits required to represent number:  5  ==>> number = 16, in bits: 10000 i.e 5 bits

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, math

Leave a Reply

Your email address will not be published. Required fields are marked *