How do I convert a hex string to a byte slice in Go?

Linda Hamilton
Release: 2024-11-13 06:04:01
Original
1069 people have browsed it

How do I convert a hex string to a byte slice in Go?

Transferring Hex Strings to []byte in Go

Converting a hex string into a slice of bytes []byte can be easily achieved in Go using the hex.DecodeString() function. This function takes a hex string representation as a parameter and returns a byte slice containing the decoded bytes corresponding to the hex characters.

Example:

Consider the following example where we want to convert the hex string "46447381" into a byte slice:

package main

import (
    "fmt"
    "encoding/hex"
)

func main() {
    s := "46447381"

    data, err := hex.DecodeString(s)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%x", data)
}
Copy after login

Explanation:

  • Import the encoding/hex package.
  • Decode the hex string using DecodeString() and store the result in the data variable.
  • Print the data slice in hexadecimal format using fmt.Printf("%x", data).

Output:

46447381
Copy after login

Note:

It's important to note that when printing the byte slice directly using fmt.Println(data), the output will be in decimal format. To print the bytes in hexadecimal format, you should use fmt.Printf("%x", data) instead.

The above is the detailed content of How do I convert a hex string to a byte slice 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template