Home >Backend Development >Golang >How Can I Decode Hex Strings into []byte Slices in Go?

How Can I Decode Hex Strings into []byte Slices in Go?

DDD
DDDOriginal
2024-11-13 04:16:02931browse

How Can I Decode Hex Strings into []byte Slices in Go?

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!

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