user1933049
user1933049

Reputation: 73

How to convert int64 to binary and keep leading zeros in golang?

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!

Upvotes: 4

Views: 4618

Answers (2)

coredump
coredump

Reputation: 38809

You can format directly as binary with padding:

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

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

Upvotes: 9

abhink
abhink

Reputation: 9126

You can try this:

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

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

Upvotes: 0

Related Questions