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
Release: 2024-11-13 04:16:02
Original
972 people have browsed it

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)
Copy after login

Output:

46 44 73 81
Copy after login

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)
Copy after login

Output:

[70 68 115 129]
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template