convert a number from base 10 to base 16 in go

To convert a number from decimal (base 10) to hexadecimal (base 16) in Go, we can use the strconv package which provides a function called FormatInt that takes an integer and a base as arguments and returns the string representation of the integer in the given base.

Here is an example code snippet that converts a decimal number to a hexadecimal string:

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// decimal number to convert
	num := 52526

	// convert to hexadecimal string
	hex := strconv.FormatInt(int64(num), 16)

	// print the result
	fmt.Printf("Decimal %d is equivalent to hexadecimal %s\n", num, hex)
}
273 chars
18 lines

In this code snippet, we first define the decimal value we want to convert (52526) as an integer. Then, we use the FormatInt function of strconv package to convert this number to a hexadecimal string. The second argument to theFormatInt function specifies the base we want to use which is 16 in this case. Finally, we print the original decimal number along with its equivalent hexadecimal value.

The output of this program will be:

main.go
Decimal 52526 is equivalent to hexadecimal cdce
48 chars
2 lines

gistlibby LogSnag