Convert Byte to Hex and Hex to Byte in Golang

Saturday, July 18, 2020 • 2 minutes to read

Tutorialto-the-point2020Golanggolangto-the-pointconversion

In this post of to-the-point series, we will convert a hex string to a byte array and vice-versa. For this, we're going to use the encoding/hex package provided by the golang. Package hex implements hexadecimal encoding and decoding.

byte array to hex string

To convert a byte array to hex string, we will encode the byte array to the hexadecimal string.

Syntax

1func EncodeToString(src []byte) string

First we will convert a string to a byte array.

 1package main
 2
 3import (
 4	"encoding/hex"
 5	"fmt"
 6)
 7
 8func main() {
 9	byteArray := []byte("Learn Go!")
10	fmt.Println("byteArray: ", byteArray)
11
12	encodedString := hex.EncodeToString(byteArray)
13
14	fmt.Println("Encoded Hex String: ", encodedString)
15}

Output

1byteArray: [76 101 97 114 110 32 71 111 33]
2Encoded Hex String: 4c6561726e20476f21

Try it

hex string to byte array

To convert hex string to byte array, we will decode the encoded hex string.

Syntax

1func DecodeString(s string) ([]byte, error)

We are going to use the same hex string from above.

 1package main
 2
 3import (
 4	"encoding/hex"
 5	"fmt"
 6)
 7
 8func main() {
 9	hexString := "4c6561726e20476f21"
10
11	fmt.Println("Hex String: ", hexString)
12
13	decodedByteArray, err := hex.DecodeString(hexString)
14
15	if err != nil {
16		fmt.Println("Unable to convert hex to byte. ", err)
17	}
18
19	fmt.Printf("Decoded Byte Array: %v \nDecoded String: %s", decodedByteArray, decodedByteArray)
20}

Try it

Output

1Hex String:  4c6561726e20476f21
2Decoded Byte Array: [76 101 97 114 110 32 71 111 33]
3Decoded String: Learn Go!

Tutorialto-the-point2020Golanggolangto-the-pointconversion

PreviousRemove an Element From an Array Using Filter in Nodejs

NextCreate an Account in Sendinblue