I am trying to do something like this:
bytes := [4]byte{1,2,3,4}
str := convert(bytes)
//str == "1,2,3,4"
I searched a lot and really have no idea how to do this.
I know this will not work:
str = string(bytes[:])
Given a bytes object, you can use the built-in decode() method to convert the byte to a string. You can also pass the encoding type to this function as an argument. For example, let's use the UTF-8 encoding for converting bytes to a string: byte_string = b"Do you want a slice of \xf0\x9f\x8d\x95?"
A byte refers to an 8-bit unsigned integer. Bytes are very common when working with slices. In go, we can convert a string to a byte using the byte() function. The function syntax is as shown: []byte(string)
A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.
using strings.Builder
would be the most efficient way to do the same..
package main
import (
"fmt"
"strings"
)
func convert( bytes []byte) string {
var str strings.Builder
for _, b := range bytes {
fmt.Fprintf(&str, "%d,", int(b))
}
return str.String()[:str.Len() - 1]
}
func main(){
s := [4]byte{1,2,3,4}
fmt.Println(convert(s[:]))
}
=> 1,2,3,4
Not the most efficient way to implement it, but you can simply write:
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,",")
}
to be called by:
bytes := [4]byte{1,2,3,4}
str := convert(bytes[:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With