convert a byte to string in golang

2019-02-11 10:23发布

I am new to golang, try to do something like this:

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

//str == "1,2,3,4"

searched a lot, really no idea how to do this.

I know this will not work:

str = string(bytes[:])

4条回答
你好瞎i
2楼-- · 2019-02-11 11:03

Similar to inf's suggestion but allowing for commas:

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

查看更多
再贱就再见
3楼-- · 2019-02-11 11:11

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[:])
查看更多
Rolldiameter
4楼-- · 2019-02-11 11:17

hex.EncodeToString(input) may work for you.

查看更多
We Are One
5楼-- · 2019-02-11 11:28

If you are not bound to the exact representation then you can use 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.

查看更多
登录 后发表回答