Home > Backend Development > Golang > How to Convert Hexadecimal Strings to Byte Arrays in Go?

How to Convert Hexadecimal Strings to Byte Arrays in Go?

Barbara Streisand
Release: 2024-11-14 17:09:02
Original
448 people have browsed it

How to Convert Hexadecimal Strings to Byte Arrays in Go?

Transferring Hexadecimal Strings to Byte Arrays in Go

Converting hexadecimal strings to byte arrays in Go is a common task in various programming scenarios. This article demonstrates a straightforward method to achieve this using the hex.DecodeString() function.

The problem at hand is to convert the hexadecimal string "46447381" into a byte array representing the individual hexadecimal values: {0x46, 0x44, 0x73, 0x81}.

The solution to this problem lies in leveraging the hex.DecodeString() function:

package main

import (
    "encoding/hex"
    "fmt"
)

func main() {
    s := "46447381"

    data, err := hex.DecodeString(s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("% x", data)
}
Copy after login

Explanation:

  1. The hex.DecodeString() function takes a hexadecimal string as input and returns a byte slice containing the decoded hexadecimal values.
  2. The decoded byte slice, data, is then printed using fmt.Printf("% x", data) to display the values in hexadecimal format.

Output:

46 44 73 81
Copy after login

Note:

It's important to remember that simply printing the byte slice using fmt.Println(data) will output the values in decimal format instead of hexadecimal. Therefore, using fmt.Printf("% x", data) is crucial to display the hexadecimal values accurately.

The above is the detailed content of How to Convert Hexadecimal Strings to Byte Arrays 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