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

How to Convert Hex Strings to Byte Arrays in Go?

Barbara Streisand
Release: 2024-11-15 13:26:02
Original
438 people have browsed it

How to Convert Hex Strings to Byte Arrays in Go?

Efficiently Converting Hex Strings to Byte Arrays in Go

In Go, converting hexadecimal strings directly to byte arrays presents a straightforward solution. Suppose you have a hex string like "46447381" and aim to transform it into a byte array consisting of [0x46, 0x44, 0x73, 0x81]. The resolution lies within the hex.DecodeString() function.

s := "46447381"

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

By utilizing this function, the code flawlessly translates the hex string into its corresponding byte array, which is then printed in hexadecimal format.

Output:

46 44 73 81
Copy after login

To clarify, if you simply print the byte slice using fmt.Println(data), the output will appear in decimal format:

[70 68 115 129]
Copy after login

However, these decimal values represent the same numbers as in the hexadecimal representation.

Remember, hex.DecodeString() offers an efficient method for converting hex strings to byte arrays, saving you time and ensuring accuracy in data conversion tasks.

The above is the detailed content of How to Convert Hex 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