How to Convert a Hexadecimal String to a Byte Array in Go?

Barbara Streisand
Release: 2024-11-21 07:59:10
Original
236 people have browsed it

How to Convert a Hexadecimal String to a Byte Array in Go?

Transferring Hex Strings to Byte Arrays in Go

Converting hexadecimal strings directly into byte arrays in Go is straightforward with the hex.DecodeString() function.

Question: How do we convert the hexadecimal string "46447381" into the byte array {0x46,0x44,0x73,0x81}?

Answer:

package main

import (
    "encoding/hex"
    "fmt"
)

func main() {
    s := "46447381"

    // Decode the hexadecimal string into a byte array
    data, err := hex.DecodeString(s)
    if err != nil {
        panic(err)
    }

    // Print the byte array in hexadecimal format
    fmt.Printf("% x", data)
}
Copy after login

Output:

46 44 73 81
Copy after login

Note: When printing the byte array directly using fmt.Println(data), the output will be in decimal format:

[70 68 115 129]
Copy after login

However, these numbers represent the same hexadecimal values in a different base.

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