Home  >  Article  >  Backend Development  >  How do I convert a hex string to a byte slice in Go?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 06:04:011078browse

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)
}

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

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!

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