convert a number from base 10 to base 2 in go

To convert a number from base 10 to base 2 (binary) in Go, we can use the strconv package.

Here's an example code snippet:

main.go
package main

import (
	"fmt"
	"strconv"
)

func decimalToBinary(decimalNum int64) string {
	binaryStr := strconv.FormatInt(decimalNum, 2)
	return binaryStr
}

func main() {
	decimalNum := int64(10)
	binaryNum := decimalToBinary(decimalNum)
	fmt.Printf("Decimal %d is Binary %s", decimalNum, binaryNum)
}
305 chars
18 lines

In this code, we first import the "fmt" and "strconv" packages.

decimalToBinary() function takes an integer of base 10 and converts it to a binary string using strconv.FormatInt() function.

And finally, in the main() function, we call decimalToBinary() function with input of type int64 and print the output.

Output of the above code snippet will be:

main.go
Decimal 10 is Binary 1010
26 chars
2 lines

gistlibby LogSnag