Home > Backend Development > Golang > How Do I Efficiently Convert a Byte Array to a Comma-Separated String in Go?

How Do I Efficiently Convert a Byte Array to a Comma-Separated String in Go?

Patricia Arquette
Release: 2024-12-17 09:51:25
Original
179 people have browsed it

How Do I Efficiently Convert a Byte Array to a Comma-Separated String in Go?

Converting Bytes to Strings in Go

In Go, you may encounter the need to convert an array of bytes to a single string. While the intuitive approach of casting the byte array directly to a string (e.g., str = string(bytes[:])) may seem straightforward, it yields an incorrect result.

Solution:

To achieve this conversion, you can harness the power of the strconv and strings packages. Here's an efficient solution:

func convert(b []byte) string {
    s := make([]string, len(b))
    for i := range b {
        s[i] = strconv.Itoa(int(b[i]))
    }
    return strings.Join(s, ",")
}
Copy after login

Usage:

Once you have defined the convert function, you can utilize it like so:

bytes := [4]byte{1, 2, 3, 4}
str := convert(bytes[:])
Copy after login

This will return a string containing the individual byte values separated by commas, resulting in the desired output: "1,2,3,4".

The above is the detailed content of How Do I Efficiently Convert a Byte Array to a Comma-Separated String 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