Home > Article > Backend Development > How to Convert a Hexadecimal String to a Byte Array in Go?
Transferring Hex Strings to Byte Arrays in Go
Converting hexadecimal strings directly into byte arrays in Go is straightforward with the hex.DecodeString() function.
Question: How do we convert the hexadecimal string "46447381" into the byte array {0x46,0x44,0x73,0x81}?
Answer:
package main import ( "encoding/hex" "fmt" ) func main() { s := "46447381" // Decode the hexadecimal string into a byte array data, err := hex.DecodeString(s) if err != nil { panic(err) } // Print the byte array in hexadecimal format fmt.Printf("% x", data) }
Output:
46 44 73 81
Note: When printing the byte array directly using fmt.Println(data), the output will be in decimal format:
[70 68 115 129]
However, these numbers represent the same hexadecimal values in a different base.
The above is the detailed content of How to Convert a Hexadecimal String to a Byte Array in Go?. For more information, please follow other related articles on the PHP Chinese website!