Home > Article > Backend Development > How to Convert Hexadecimal Strings to Byte Arrays in Go?
Transferring Hexadecimal Strings to Byte Arrays in Go
Converting hexadecimal strings to byte arrays in Go is a common task in various programming scenarios. This article demonstrates a straightforward method to achieve this using the hex.DecodeString() function.
The problem at hand is to convert the hexadecimal string "46447381" into a byte array representing the individual hexadecimal values: {0x46, 0x44, 0x73, 0x81}.
The solution to this problem lies in leveraging the hex.DecodeString() function:
package main import ( "encoding/hex" "fmt" ) func main() { s := "46447381" data, err := hex.DecodeString(s) if err != nil { panic(err) } fmt.Printf("% x", data) }
Explanation:
Output:
46 44 73 81
Note:
It's important to remember that simply printing the byte slice using fmt.Println(data) will output the values in decimal format instead of hexadecimal. Therefore, using fmt.Printf("% x", data) is crucial to display the hexadecimal values accurately.
The above is the detailed content of How to Convert Hexadecimal Strings to Byte Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!