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, ",") }
Usage:
Once you have defined the convert function, you can utilize it like so:
bytes := [4]byte{1, 2, 3, 4} str := convert(bytes[:])
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!