convert a number from base 2 to base 8 in go

To convert a number from base 2 to base 8 in go, we can use the strconv package which provides functions to convert strings to different numeric formats. Here's an example code that converts a binary number to an octal:

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	binary := "10101010" // binary number
	decimal, err := strconv.ParseInt(binary, 2, 64)
	if err != nil {
		panic(err)
	}
	octal := strconv.FormatInt(decimal, 8)

	fmt.Printf("Binary: %s\nOctal: %s", binary, octal)
}
274 chars
18 lines

The strconv.ParseInt function takes three arguments - the input string, the base to convert from (in this case 2 for binary) and the bit size (in this case 64). It returns the decimal equivalent of the input string.

The strconv.FormatInt function takes two arguments - the decimal number to convert and the base to convert to (in this case 8 for octal). It returns a string representing the decimal number in the desired base.

The output of the above code would be:

main.go
Binary: 10101010
Octal: 252
28 chars
3 lines

gistlibby LogSnag