How to convert hex to string in Golang

  • 12 April 2019
  • ADM

 

How to convert hex to string in Golang - images/logos/golang.jpg

 

Here is a simple snippet of how to convert hex into a string type in Golang. If you need help how to install Golang check the references links.

Code

To convert hex into a string, use the DecodeString method from encoding/hex package.

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	//the encoded value of string: Hello from ADMFactory.com
	str := "48656c6c6f2066726f6d2041444d466163746f72792e636f6d"
	bs, err := hex.DecodeString(str)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(bs))
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build hexToString.go

Then depending if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./hexToString

Windows

c:\Users\adm\go\tutorials> hexToString.exe

If you want to compile and run the application in one single step run the following command:

$ go run hexToString.go

Output

Will display the br variable value Hello from ADMFactory.com.

Hello from ADMFactory.com

 

References