convert a number from base 10 to base 8 in go

To convert a number from base 10 to base 8 in go, we can use the strconv package. Here's an example code snippet:

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 42
	base := 8

	result := strconv.FormatInt(int64(num), base)

	fmt.Println("Decimal:", num)
	fmt.Println("Octal:", result)
}
192 chars
17 lines

In this code, we have a decimal number 42 stored in the num variable, and we want to convert it to base 8 (octal). We pass the num variable to the FormatInt function of the strconv package along with the base (8). This function returns the octal representation of the decimal number as a string. We then print out both the decimal and octal representations of the number using the fmt package.

The output of this code would be:

main.go
Decimal: 42
Octal: 52
22 chars
3 lines

gistlibby LogSnag