Apr 152019

ADM

How to convert string to hex string in Golang

  • April 15 2019
  • ADM

 

 

How to convert string to hex string in Golang - golang

 

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

Code

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

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	str := "Hello from ADMFactory.com"
	hx := hex.EncodeToString([]byte(str))
	fmt.Println("String to Hex Golang example")
	fmt.Println()
	fmt.Println(str + " ==> " + hx)
}

Compile&Run

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

$ go build stringToHexString.go

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

To run the application execute the command.

Linux

$ ./stringToHexString

Windows

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

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

go run stringToHexString.go

Output

Will display the following output.

String to Hex Golang example

Hello from ADMFactory.com ==> 48656c6c6f2066726f6d2041444d466163746f72792e636f6d

References