convert a number from base 2 to base 16 in go

One way to convert a number from base 2 (binary) to base 16 (hexadecimal) in Go is to use the strconv package. Specifically, we can use the ParseInt() function to convert the binary number to an integer, and then use the FormatInt() function to format the integer as a hexadecimal string.

Here's an example code snippet that demonstrates how to convert the binary number "10101010" (which is 170 in decimal) to a hexadecimal string:

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// binary number to convert
	binaryStr := "10101010"

	// parse binary number as an integer
	binaryInt, err := strconv.ParseInt(binaryStr, 2, 64)
	if err != nil {
		panic(err)
	}

	// format integer as hexadecimal string
	hexStr := strconv.FormatInt(binaryInt, 16)

	// print result
	fmt.Printf("Binary %s = Hexadecimal %s", binaryStr, hexStr)
}
405 chars
24 lines

When we run this program, the output should be:

main.go
Binary 10101010 = Hexadecimal aa
33 chars
2 lines

Note that the strconv.ParseInt() function takes three arguments: the string to parse, the base of the number (which is 2 for binary), and the bit size of the resulting integer (which we set to 64 because we don't know how big the binary number might be).

Similarly, the strconv.FormatInt() function takes two arguments: the integer to format, and the base of the resulting string (which is 16 for hexadecimal).

gistlibby LogSnag