Converting from an integer to its binary representation

Solution 1:

The strconv package has FormatInt, which accepts an int64 and lets you specify the base.

n := int64(123)

fmt.Println(strconv.FormatInt(n, 2)) // 1111011

DEMO: http://play.golang.org/p/leGVAELMhv

http://golang.org/pkg/strconv/#FormatInt

func FormatInt(i int64, base int) string

FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

Solution 2:

See also the fmt package:

n := int64(123)
fmt.Printf("%b", n)  // 1111011

Solution 3:

package main

import . "fmt"

func main(){
    Printf("%d == %08b\n",0,0)
    Printf("%d == %08b\n",1,1)
    Printf("%d == %08b\n",2,2)
    Printf("%d == %08b\n",3,3)
    Printf("%d == %08b\n",4,4)
    Printf("%d == %08b\n",5,5)
}

results in:

0 == 00000000
1 == 00000001
2 == 00000010
3 == 00000011
4 == 00000100
5 == 00000101