hakk

software development, devops, and other drivel
Tree lined path

Golang Convert from Int to Hex

Converting from an Integer to hex is easy in Golang. Since a hex is really just an Integer literal, you can ask the fmt package for a string representation of that integer, using fmt.Sprintf(), and the %x or %X format.

package main

import (
	"fmt"
)

func main() {
	for i := 1; i < 20; i++ {
		h := fmt.Sprintf("0x%x", i)
		fmt.Println(h)
	}
}

Golang Play

Output:

0x1
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xa
0xb
0xc
0xd
0xe
0xf
0x10
0x11
0x12
0x13

Convert back to int

package main

import (
	"fmt"
	"strconv"
)
	
var hex = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "10", "11", "12", "13"}

func main() {
	for _, h := range hex {
		i, _ := strconv.ParseInt(h, 16, 64)
		fmt.Println(i)
	}
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19