Home >Backend Development >Golang >golang string to hex
In the Go language, to convert a string into a hexadecimal string, that is, to encode the string into a string in hexadecimal format, you can use the hex
package in the standard library. hex
Package provides functions to convert byte arrays and strings to hexadecimal strings.
The following describes how to convert a string into a hexadecimal string.
Sample code:
package main import ( "encoding/hex" "fmt" ) func main() { str := "hello world" encodedStr := hex.EncodeToString([]byte(str)) fmt.Println(encodedStr) }
Running result:
68656c6c6f20776f726c64
Sample code:
package main import "fmt" func main() { str := "hello world" hexStr := "" for _, c := range str { hexStr += fmt.Sprintf("%x", c) } fmt.Println(hexStr) }
Running result:
68656c6c6f20776f726c64
In the above code, we use a for loop to traverse the string Each character, then use the Sprintf
function to format the character into a hexadecimal string, and finally splice the hexadecimal value of each character to obtain the final hexadecimal string.
It should be noted that the Sprintf
function used in the above code uses UTF-8 encoding when converting characters into hexadecimal strings. If you need to use other encoding methods, you can use the strconv
function in the standard library.
Summary:
In Go language, to convert a string into a hexadecimal string, you can use the function provided by the hex
package, or use a loop to traverse the string and convert each character into a hexadecimal string. Both methods can get the desired results. It may be simpler and more efficient to use the functions provided by the hex
package.
The above is the detailed content of golang string to hex. For more information, please follow other related articles on the PHP Chinese website!