Decoding Hex Strings into []byte Slices in Go
In Go, there is a convenient way to convert hexadecimal strings into slices of bytes. This can be useful when dealing with binary data represented as hex strings or when you need to parse data encoded in this format.
The hex.DecodeString() function in the encoding/hex package is the solution. It takes a hexadecimal string as input and returns a byte slice containing the decoded data. The following example demonstrates its usage:
s := "46447381" data, err := hex.DecodeString(s) if err != nil { panic(err) } fmt.Printf("% x", data)
Output:
46 44 73 81
However, it's important to note that if you directly print the byte slice using fmt.Println(data), the values will be in decimal format, not hexadecimal.
fmt.Println(data)
Output:
[70 68 115 129]
These values represent the same numbers, just in decimal base.
The above is the detailed content of How Can I Decode Hex Strings into []byte Slices in Go?. For more information, please follow other related articles on the PHP Chinese website!