在golang中将一个字节转换为字符串

ZHA*_*ong 5 arrays string byte go

我是golang的新手,尝试做这样的事情:

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

//str == "1,2,3,4"
Run Code Online (Sandbox Code Playgroud)

搜索了很多,真的不知道怎么做.

我知道这不起作用:

str = string(bytes[:])
Run Code Online (Sandbox Code Playgroud)

Did*_*zia 10

不是最有效的实现方式,但你可以简单地写:

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,",")
}
Run Code Online (Sandbox Code Playgroud)

被称为:

bytes := [4]byte{1,2,3,4}
str := convert(bytes[:])
Run Code Online (Sandbox Code Playgroud)


inf*_*inf 6

如果您不受确切表示的约束,那么您可以使用fmt.Sprint:

fmt.Sprint(bytes) // [1 2 3 4]
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你想要你的确切逗号样式,那么你必须自己使用循环来构建它strconv.Itoa.


Dan*_*and 5

类似于 inf 的建议,但允许使用逗号:

fmt.Sprintf("%d,%d,%d,%d", bytes[0], bytes[1], bytes[2], bytes[3])