3

I have created a program which converts int64 to binary:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    n := int64(3)
    fmt.Println(strconv.FormatInt(n, 2))
}

And it returns this value:

11

How can I keep the leading zeros in the answer?

Thanks in advance!

user1933049
  • 63
  • 1
  • 4
  • 2
    Possible duplicate of [Golang: How to pad a number with zeros when printing?](http://stackoverflow.com/questions/25637440/golang-how-to-pad-a-number-with-zeros-when-printing) – coredump Jul 17 '16 at 16:20
  • See https://play.golang.org/p/lS0DoMLth6 – coredump Jul 17 '16 at 16:21

2 Answers2

8

You can format directly as binary with padding:

fmt.Printf("%064b\n", n)

See https://play.golang.org/p/JHCgyPMKDG

coredump
  • 37,664
  • 5
  • 43
  • 77
0

You can try this:

func main() {
    n := int64(3)
    s := strconv.FormatInt(n, 2)
    fmt.Printf("%064s", s)
}

https://play.golang.org/p/23IGYPYaE8

abhink
  • 8,740
  • 1
  • 36
  • 48