string 在 Go 中将字节转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31220421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:24:29  来源:igfitidea点击:

Convert a byte to a string in Go

arraysstringgobyte

提问by ZHAO Xudong

I am new to Go and trying to do something like this:

我是 Go 的新手并试图做这样的事情:

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[:])

回答by Didier Spezia

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[:])

回答by Stephan Dollberg

If you are not bound to the exact representation then you can use fmt.Sprint:

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

fmt.Sprint(bytes) // [1 2 3 4]

On the other side if you want your exact comma style then you have to build it yourself using a loop together with strconv.Itoa.

另一方面,如果您想要确切的逗号样式,则必须使用循环和strconv.Itoa.

回答by Dan Garland

Similar to inf's suggestion but allowing for commas:

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

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

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

回答by BlockedMan

hex.EncodeToString(input)may work for you.

hex.EncodeToString(input)可能对你有用。