Home >Backend Development >Golang >golang string to hex

golang string to hex

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2023-05-10 10:31:361540browse

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. hexPackage provides functions to convert byte arrays and strings to hexadecimal strings.

The following describes how to convert a string into a hexadecimal string.

  1. Use the EncodeToString function of the hex package

Sample code:

package main

import (
    "encoding/hex"
    "fmt"
)

func main() {
    str := "hello world"
    encodedStr := hex.EncodeToString([]byte(str))
    fmt.Println(encodedStr)
}

Running result:

68656c6c6f20776f726c64
  1. Traverse the string And converted to hexadecimal

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to call c in golangNext article:How to call c in golang