Home > Article > Backend Development > How do I convert a hex string to a byte slice in Go?
Transferring Hex Strings to []byte in Go
Converting a hex string into a slice of bytes []byte can be easily achieved in Go using the hex.DecodeString() function. This function takes a hex string representation as a parameter and returns a byte slice containing the decoded bytes corresponding to the hex characters.
Example:
Consider the following example where we want to convert the hex string "46447381" into a byte slice:
package main import ( "fmt" "encoding/hex" ) func main() { s := "46447381" data, err := hex.DecodeString(s) if err != nil { panic(err) } fmt.Printf("%x", data) }
Explanation:
Output:
46447381
Note:
It's important to note that when printing the byte slice directly using fmt.Println(data), the output will be in decimal format. To print the bytes in hexadecimal format, you should use fmt.Printf("%x", data) instead.
The above is the detailed content of How do I convert a hex string to a byte slice in Go?. For more information, please follow other related articles on the PHP Chinese website!