How can I get binary representation of an integer in Go?

Suppose I want to get binary representation of an integer say 1024 as 10000000000. How do I do that in Golang?

  1. Accepted Answer

Accepted Answer

Using strconv.FormatInt

The strconv package has a function called FormatInt that returns the string representation of a number in the given base. In your case, you can do the following:

n := int64(1024)
fmt.Println(strconv.FormatInt(n, 2)) //print n in base-2

This outputs 10000000000. You can find more information on the method here https://pkg.go.dev/strconv#FormatInt

Speak Your Mind